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

相关文章

java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)

《java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)》:本文主要介绍java中pdf模版填充表单踩坑的相关资料,OpenPDF、iText、PDFBox是三... 目录准备Pdf模版方法1:itextpdf7填充表单(1)加入依赖(2)代码(3)遇到的问题方法2:pd

Java Stream流之GroupBy的用法及应用场景

《JavaStream流之GroupBy的用法及应用场景》本教程将详细介绍如何在Java中使用Stream流的groupby方法,包括基本用法和一些常见的实际应用场景,感兴趣的朋友一起看看吧... 目录Java Stream流之GroupBy的用法1. 前言2. 基础概念什么是 GroupBy?Stream

Python操作PDF文档的主流库使用指南

《Python操作PDF文档的主流库使用指南》PDF因其跨平台、格式固定的特性成为文档交换的标准,然而,由于其复杂的内部结构,程序化操作PDF一直是个挑战,本文主要为大家整理了Python操作PD... 目录一、 基础操作1.PyPDF2 (及其继任者 pypdf)2.PyMuPDF / fitz3.Fre

SpringBoot监控API请求耗时的6中解决解决方案

《SpringBoot监控API请求耗时的6中解决解决方案》本文介绍SpringBoot中记录API请求耗时的6种方案,包括手动埋点、AOP切面、拦截器、Filter、事件监听、Micrometer+... 目录1. 简介2.实战案例2.1 手动记录2.2 自定义AOP记录2.3 拦截器技术2.4 使用Fi

最新Spring Security的基于内存用户认证方式

《最新SpringSecurity的基于内存用户认证方式》本文讲解SpringSecurity内存认证配置,适用于开发、测试等场景,通过代码创建用户及权限管理,支持密码加密,虽简单但不持久化,生产环... 目录1. 前言2. 因何选择内存认证?3. 基础配置实战❶ 创建Spring Security配置文件

Spring Security 单点登录与自动登录机制的实现原理

《SpringSecurity单点登录与自动登录机制的实现原理》本文探讨SpringSecurity实现单点登录(SSO)与自动登录机制,涵盖JWT跨系统认证、RememberMe持久化Token... 目录一、核心概念解析1.1 单点登录(SSO)1.2 自动登录(Remember Me)二、代码分析三、

springboot自定义注解RateLimiter限流注解技术文档详解

《springboot自定义注解RateLimiter限流注解技术文档详解》文章介绍了限流技术的概念、作用及实现方式,通过SpringAOP拦截方法、缓存存储计数器,结合注解、枚举、异常类等核心组件,... 目录什么是限流系统架构核心组件详解1. 限流注解 (@RateLimiter)2. 限流类型枚举 (

Java Thread中join方法使用举例详解

《JavaThread中join方法使用举例详解》JavaThread中join()方法主要是让调用改方法的thread完成run方法里面的东西后,在执行join()方法后面的代码,这篇文章主要介绍... 目录前言1.join()方法的定义和作用2.join()方法的三个重载版本3.join()方法的工作原

Spring AI使用tool Calling和MCP的示例详解

《SpringAI使用toolCalling和MCP的示例详解》SpringAI1.0.0.M6引入ToolCalling与MCP协议,提升AI与工具交互的扩展性与标准化,支持信息检索、行动执行等... 目录深入探索 Spring AI聊天接口示例Function CallingMCPSTDIOSSE结束语

Java获取当前时间String类型和Date类型方式

《Java获取当前时间String类型和Date类型方式》:本文主要介绍Java获取当前时间String类型和Date类型方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录Java获取当前时间String和Date类型String类型和Date类型输出结果总结Java获取