Java利用docx4j+Freemarker生成word文档

2025-04-08 04:50

本文主要是介绍Java利用docx4j+Freemarker生成word文档,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《Java利用docx4j+Freemarker生成word文档》这篇文章主要为大家详细介绍了Java如何利用docx4j+Freemarker生成word文档,文中的示例代码讲解详细,感兴趣的小伙伴...

技术方案

Java 1.8 + docx4j + Freemarker

maven依赖

<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.31</version> <!-- 请使用最新版本 -->
</dependency>

<!-- https://mvnrepository.com/China编程artifact/org.docx4j/docx4j -->
<dependency>
    <groupId>org.docx4j</groupId>
    <artifactId>docx4j</artifactId>
    <version>6.1.2</version>
</dependency>
<dependency>
    <groupId>org.docx4j</groupId>
    <artifactId>docx4j-ImportXhtml</artifactId>
    <version>6.1.0</version>
</dependency>
<!-- slf4j for logging -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.7.36</version>
</dependency>

创建模板文件

保存至src/main/resources/templates/,文件名为template.html

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8"></meta>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"></meta>
    <title>${name}的简历</title>
    <style>
        @page {
            size: A4;
            margin: 5mm 10mm; /* 上下和左右两个方向的边距分别为 10mm 和 20mm */
        }
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f4f4f9;
        }
        .container {
            width: 80%;
            margin: 0 auto;
            padding: 20px;
            background-color: #ffffff;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        h1 {
            text-align: center;
            color: #333;
        }
        .section-title {
            color: #4CAF50;
            margin-top: 20px;
        }
        .section-content {
            margin: 10px 0;
        }
        .contact-info, .skills, .experience, .education {
            margin-bottom: 20px;
        }
        .experience, .education {
            margin-top: 10px;
        }
        ul {
            list-style-type: none;
            padding-left: 0;
        }
        li {
            margin-bottom: 10px;
        }
        .job, .degree {
            font-weight: bold;
        }
    </style>
</head>



<body>

<div class="container">
    <h1>${name}的简历</h1>

    <!-- 联系信息 -->
    <div class="contact-info">
        <h2 class="section-title">联系信息</h2>
      www.chinasem.cn  <p>邮箱: ${email}</p>
        <p>电话: ${phone}</p>
    </div>

    <!-- 工作经历 -->
    <div class="experience">
        <h2 class="section-title">工作经历</h2>
        <#list experience as job>
        <div class="job">
            <p><strong>${job.position}</strong> 在 ${job.company}(${job.startYear} - ${job.endYear})</p>
            <p>${job.description}</p>
        </div>
        </#list>
    </div>

    <!-- 教育背景 -->
    <div class="education">
        <h2 class="section-title">教育背景</h2>
        <#list education as degree>
            <div class="degree">
                <p><strong>${degree.degree}</strong> ${degree.school}(${degree.year}年)</p>
            </div>
        </#list>
    </div>
</div>

</body>
</html>

实现代码

package com.ruoyi.system.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.docx4j.Docx4J;
import org.docx4j.convert.in.Xhtml.XHTMLImporterImpl;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.exceptions.InvalidFormatException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;

import java.io.File;
import java.io.IOException;
import java.ijavascripto.StrinandroidgWriter;
import java.util.Map;

/**
 * @Program: RuoYi-master
 * @ClassName: GenerateWord
 * @author: zhouzihao
 * @date: 2025年2月20日, 0020 下午 03:25
 * @version: 1.0.0
 * @Description:
 * @Time: 2025-02-20 15:25
 */
public class GenerateWordUtil {
    // 模板路径
    private static final String templatesPath = "/templates";
    // 模板文件
    private static final String templatesFile = "template.html";

    public static void generateWord(Map<String, Object> data, String filePName) {
        // 配置 Freemarker
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_30);
        cfg.setClassForTemplateLoading(GenerateWordUtil.class, templatesPath);

        // 获取 HTML 模板
        try {
            Template template = cfg.getTemplate(templatesFile);

            // 使用 Freemarker 填充模板
            StringWriter writer = new StringWriter();
            template.process(data, writer);
            String htmlContent = writer.toString();

            // 创建 Word 文档包
            WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
            MainDocumentPart mainDocumentPart = wordMLPackage.getMainDocumentPart();

            // 创建 XHTML 导入器实现类实例
            XHTMLImporterImpl xhtmlImporter = new XHTMLImporterImpl(wordMLPackage);

            // 将 HTMLjavascript 内容导入到 Word 文档中
            java.util.List<Object> convertedXHTML = xhtmlImporter.convert(htmlContent, null);

            // 将转换后的内容添加到文档主体中
            mainDocumentPart.getContent().addAll(convertedXHTML);

            // 保存生成的 Word 文档
            File outputFile = new File(filePName);
            Docx4J.save(wordMLPackage, outputFile, Docx4J.FLAG_NONE);
            System.out.println("Word 文档生成成功:" + outputFile.getAbsolutePath());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (TemplateException e) {
            throw new RuntimeException(e);
        } catch (InvalidFormatException e) {
            throw new RuntimeException(e);
        } catch (Docx4JException e) {
            throw new RuntimeException(e);
        }

    }

}

到此这篇关于Java利用docx4j+Freemarker生成word文档的文章就介绍到这了,更多相关Java生成word内容请搜索China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程China编程(www.chinasem.cn)!

这篇关于Java利用docx4j+Freemarker生成word文档的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1154123

相关文章

SpringBoot中六种批量更新Mysql的方式效率对比分析

《SpringBoot中六种批量更新Mysql的方式效率对比分析》文章比较了MySQL大数据量批量更新的多种方法,指出REPLACEINTO和ONDUPLICATEKEY效率最高但存在数据风险,MyB... 目录效率比较测试结构数据库初始化测试数据批量修改方案第一种 for第二种 case when第三种

python生成随机唯一id的几种实现方法

《python生成随机唯一id的几种实现方法》在Python中生成随机唯一ID有多种方法,根据不同的需求场景可以选择最适合的方案,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习... 目录方法 1:使用 UUID 模块(推荐)方法 2:使用 Secrets 模块(安全敏感场景)方法

Java docx4j高效处理Word文档的实战指南

《Javadocx4j高效处理Word文档的实战指南》对于需要在Java应用程序中生成、修改或处理Word文档的开发者来说,docx4j是一个强大而专业的选择,下面我们就来看看docx4j的具体使用... 目录引言一、环境准备与基础配置1.1 Maven依赖配置1.2 初始化测试类二、增强版文档操作示例2.

一文详解如何使用Java获取PDF页面信息

《一文详解如何使用Java获取PDF页面信息》了解PDF页面属性是我们在处理文档、内容提取、打印设置或页面重组等任务时不可或缺的一环,下面我们就来看看如何使用Java语言获取这些信息吧... 目录引言一、安装和引入PDF处理库引入依赖二、获取 PDF 页数三、获取页面尺寸(宽高)四、获取页面旋转角度五、判断

Spring Boot中的路径变量示例详解

《SpringBoot中的路径变量示例详解》SpringBoot中PathVariable通过@PathVariable注解实现URL参数与方法参数绑定,支持多参数接收、类型转换、可选参数、默认值及... 目录一. 基本用法与参数映射1.路径定义2.参数绑定&nhttp://www.chinasem.cnbs

JAVA中安装多个JDK的方法

《JAVA中安装多个JDK的方法》文章介绍了在Windows系统上安装多个JDK版本的方法,包括下载、安装路径修改、环境变量配置(JAVA_HOME和Path),并说明如何通过调整JAVA_HOME在... 首先去oracle官网下载好两个版本不同的jdk(需要登录Oracle账号,没有可以免费注册)下载完

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

Spring Boot 结合 WxJava 实现文章上传微信公众号草稿箱与群发

《SpringBoot结合WxJava实现文章上传微信公众号草稿箱与群发》本文将详细介绍如何使用SpringBoot框架结合WxJava开发工具包,实现文章上传到微信公众号草稿箱以及群发功能,... 目录一、项目环境准备1.1 开发环境1.2 微信公众号准备二、Spring Boot 项目搭建2.1 创建

Java中Integer128陷阱

《Java中Integer128陷阱》本文主要介绍了Java中Integer与int的区别及装箱拆箱机制,重点指出-128至127范围内的Integer值会复用缓存对象,导致==比较结果为true,下... 目录一、Integer和int的联系1.1 Integer和int的区别1.2 Integer和in

SpringSecurity整合redission序列化问题小结(最新整理)

《SpringSecurity整合redission序列化问题小结(最新整理)》文章详解SpringSecurity整合Redisson时的序列化问题,指出需排除官方Jackson依赖,通过自定义反序... 目录1. 前言2. Redission配置2.1 RedissonProperties2.2 Red