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请求参数接收控制指南分享

《SpringBoot请求参数接收控制指南分享》:本文主要介绍SpringBoot请求参数接收控制指南,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Spring Boot 请求参数接收控制指南1. 概述2. 有注解时参数接收方式对比3. 无注解时接收参数默认位置

SpringBoot基于配置实现短信服务策略的动态切换

《SpringBoot基于配置实现短信服务策略的动态切换》这篇文章主要为大家详细介绍了SpringBoot在接入多个短信服务商(如阿里云、腾讯云、华为云)后,如何根据配置或环境切换使用不同的服务商,需... 目录目标功能示例配置(application.yml)配置类绑定短信发送策略接口示例:阿里云 & 腾

SpringBoot项目中报错The field screenShot exceeds its maximum permitted size of 1048576 bytes.的问题及解决

《SpringBoot项目中报错ThefieldscreenShotexceedsitsmaximumpermittedsizeof1048576bytes.的问题及解决》这篇文章... 目录项目场景问题描述原因分析解决方案总结项目场景javascript提示:项目相关背景:项目场景:基于Spring

Spring Boot 整合 SSE的高级实践(Server-Sent Events)

《SpringBoot整合SSE的高级实践(Server-SentEvents)》SSE(Server-SentEvents)是一种基于HTTP协议的单向通信机制,允许服务器向浏览器持续发送实... 目录1、简述2、Spring Boot 中的SSE实现2.1 添加依赖2.2 实现后端接口2.3 配置超时时

Spring Boot读取配置文件的五种方式小结

《SpringBoot读取配置文件的五种方式小结》SpringBoot提供了灵活多样的方式来读取配置文件,这篇文章为大家介绍了5种常见的读取方式,文中的示例代码简洁易懂,大家可以根据自己的需要进... 目录1. 配置文件位置与加载顺序2. 读取配置文件的方式汇总方式一:使用 @Value 注解读取配置方式二

一文详解Java异常处理你都了解哪些知识

《一文详解Java异常处理你都了解哪些知识》:本文主要介绍Java异常处理的相关资料,包括异常的分类、捕获和处理异常的语法、常见的异常类型以及自定义异常的实现,文中通过代码介绍的非常详细,需要的朋... 目录前言一、什么是异常二、异常的分类2.1 受检异常2.2 非受检异常三、异常处理的语法3.1 try-

Java中的@SneakyThrows注解用法详解

《Java中的@SneakyThrows注解用法详解》:本文主要介绍Java中的@SneakyThrows注解用法的相关资料,Lombok的@SneakyThrows注解简化了Java方法中的异常... 目录前言一、@SneakyThrows 简介1.1 什么是 Lombok?二、@SneakyThrows

Java中字符串转时间与时间转字符串的操作详解

《Java中字符串转时间与时间转字符串的操作详解》Java的java.time包提供了强大的日期和时间处理功能,通过DateTimeFormatter可以轻松地在日期时间对象和字符串之间进行转换,下面... 目录一、字符串转时间(一)使用预定义格式(二)自定义格式二、时间转字符串(一)使用预定义格式(二)自

Spring 请求之传递 JSON 数据的操作方法

《Spring请求之传递JSON数据的操作方法》JSON就是一种数据格式,有自己的格式和语法,使用文本表示一个对象或数组的信息,因此JSON本质是字符串,主要负责在不同的语言中数据传递和交换,这... 目录jsON 概念JSON 语法JSON 的语法JSON 的两种结构JSON 字符串和 Java 对象互转

JAVA保证HashMap线程安全的几种方式

《JAVA保证HashMap线程安全的几种方式》HashMap是线程不安全的,这意味着如果多个线程并发地访问和修改同一个HashMap实例,可能会导致数据不一致和其他线程安全问题,本文主要介绍了JAV... 目录1. 使用 Collections.synchronizedMap2. 使用 Concurren