游乐游手机版
首页/编程语言/文章详情

Java中使用模板引擎+WordXML导出复杂Word的步骤

时间:2026-05-05 22:22
处理Word文档动态生成,一个绕不开的难题就是如何优雅地融合样式与数据。直接操作Word对象模型(如Apache POI)功能强大,但代码冗长,样式控制也颇为繁琐。今天,我们来探讨一种更为“曲线救国”但极其灵活的方案:利用Word文档的XML本质,结合模板引擎来实现动态填充。 实现原理 这个方案的核

处理Word文档动态生成,一个绕不开的难题就是如何优雅地融合样式与数据。直接操作Word对象模型(如Apache POI)功能强大,但代码冗长,样式控制也颇为繁琐。今天,我们来探讨一种更为“曲线救国”但极其灵活的方案:利用Word文档的XML本质,结合模板引擎来实现动态填充。

实现原理

这个方案的核心思路非常巧妙:它利用了Word文档(无论是.doc还是.docx)本质上是一种结构化XML文档的特性。我们不必在代码里费力地调整段落格式、设置字体,而是把这件事交给最擅长的工具——Microsoft Word本身。

  1. 设计静态模板:首先,在Microsoft Word里精心设计好文档的所有样式、版式和固定内容,保存为Word 2003 XML文档格式(.xml),或者直接使用一个.docx文件(它其实是一个ZIP压缩包,核心内容在word/document.xml里)。
  2. 植入动态标记:然后,在这个XML文件里,找到需要插入动态数据的位置,嵌入模板引擎的占位符,比如${name}<#list>之类的语法。这里需要小心操作,确保这些标记不会破坏XML本身的结构。
  3. 引擎渲染数据:在Ja va程序中,读取这个“改装”过的XML文件,把它当作一个FreeMarker或Velocity模板来对待。准备好你的数据模型,让模板引擎完成渲染,动态数据就被填充到占位符的位置了。
  4. 重新打包输出:最后,将渲染得到的新XML内容,替换回原始的.docx压缩包内的对应文件,或者直接保存为最终的文档格式。一个样式完美、数据新鲜的Word文档就诞生了。

示例步骤(以 FreeMarker + docx 为例)

光说不练假把式,我们来看一个结合FreeMarker和.docx格式的具体操作流程:

  1. 准备模板:创建一个标准的.docx文件作为模板,用任何ZIP工具(或直接修改文件后缀为.zip)解压它,找到位于word/目录下的document.xml文件,这就是文档的主体内容。
  2. 编辑XML:用文本编辑器打开document.xml,在需要动态填入姓名、日期、列表数据的地方,插入FreeMarker语法。处理时要特别注意转义问题,必要时可以使用CDATA区块来包裹模板语法,以免与XML标签冲突。
  3. Ja va端渲染:在Ja va代码中,将上一步修改好的document.xml作为FreeMarker模板文件加载。构建你的数据模型(通常是一个Map),调用模板引擎进行渲染,得到一段填充好数据的XML字符串。
  4. 替换与打包:将这段新生成的XML字符串,写回之前解压的document.xml文件中,然后将整个文件夹重新打包成.zip格式,再把文件后缀改回.docx。当然,这个过程可以通过程序自动化完成。
// BeanUtil使用的是Hutool中的工具类
Map dataMap = BeanUtil.beanToMap(report);

try {
    // 1. 创建 FreeMarker 配置
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_31);
    // 模板所在目录
    cfg.setDirectoryForTemplateLoading(new File(templateDir));
    cfg.setDefaultEncoding("UTF-8");
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    cfg.setLogTemplateExceptions(false);
    cfg.setWrapUncheckedExceptions(true);
    cfg.setFallbackOnNullLoopVariable(false);

    // 2. 加载模板(已按上述要求修改的 XML 文件)
    Template template = cfg.getTemplate(templatePath);

    // 4. 渲染模板
    try (Writer out = new BufferedWriter(new OutputStreamWriter(
            new FileOutputStream(templateOutputPath), StandardCharsets.UTF_8))) {
        template.process(dataMap, out);
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        String fileName = report.getUnitName() + "年度自评报告.docx";
        String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString()).replace("+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);

        // yaml配置示例
        //yearSelfEvaluation:
        //  # 模板目录
        //  templateDir: G:\\templates
        //  # 模板路径
        //  templatePath: template\\word\\document.xml
        //  # 输出路径
        //  templateOutputPath: G:\\templates\\output2.xml
        //  # 模板docx路径
        //  templateDocxPath: G:\\templates\\template.docx

        // 调用工具类,将渲染后的XML打包成docx并通过response输出
        XmlToDocx.convert(templateDocxPath, templateOutputPath, response);
    }
} catch (Exception e) {
    log.error("渲染模板失败", e);
}



// 以下是关键的 XmlToDocx 工具类实现
import ja vax.servlet.http.HttpServletResponse;
import ja va.io.*;
import ja va.nio.charset.StandardCharsets;
import ja va.nio.file.Files;
import ja va.nio.file.Path;
import ja va.nio.file.Paths;
import ja va.util.zip.ZipEntry;
import ja va.util.zip.ZipInputStream;
import ja va.util.zip.ZipOutputStream;

public class XmlToDocx {

    /**
     * 将渲染后的 Word 2003 XML 文件内容替换到 docx 模板中,并将生成的 docx 写入 HttpServletResponse 输出流
     * @param docxTemplate    原始的 docx 模板路径(由 XML 另存得来)
     * @param renderedXmlPath 渲染后的 XML 文件路径
     * @param response        HttpServletResponse 对象,用于输出 docx
     */
    public static void convert(String docxTemplate, String renderedXmlPath, HttpServletResponse response) throws IOException {
        // 读取渲染后的 XML 文件内容(Ja va 8 兼容)
        Path xmlPath = Paths.get(renderedXmlPath);
        byte[] xmlBytes = Files.readAllBytes(xmlPath);
        String renderedXml = new String(xmlBytes, StandardCharsets.UTF_8);

        // 创建临时目录存放解压后的文件
        Path tempDir = Files.createTempDirectory("docx");
        try (ZipInputStream zis = new ZipInputStream(new FileInputStream(docxTemplate))) {
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                File outFile = new File(tempDir.toFile(), entry.getName());
                if (entry.isDirectory()) {
                    outFile.mkdirs();
                } else {
                    outFile.getParentFile().mkdirs();
                    try (FileOutputStream fos = new FileOutputStream(outFile)) {
                        byte[] buffer = new byte[8192];
                        int len;
                        while ((len = zis.read(buffer)) != -1) {
                            fos.write(buffer, 0, len);
                        }
                    }
                }
                zis.closeEntry();
            }
        }

        // 替换 document.xml
        Path docXmlPath = tempDir.resolve("word/document.xml");
        Files.write(docXmlPath, renderedXml.getBytes(StandardCharsets.UTF_8));

        // 重新打包为 docx 并直接写入 response 输出流
        try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) {
            Files.walk(tempDir).forEach(path -> {
                if (Files.isRegularFile(path)) {
                    String entryName = tempDir.relativize(path).toString().replace('\\', '/');
                    try {
                        zos.putNextEntry(new ZipEntry(entryName));
                        Files.copy(path, zos);
                        zos.closeEntry();
                    } catch (IOException e) {
                        throw new UncheckedIOException(e);
                    }
                }
            });
            zos.finish(); // 确保 ZIP 文件正确结束
        } finally {
            // 清理临时目录
            Files.walk(tempDir)
                    .map(Path::toFile)
                    .forEach(File::delete);
        }
    }

    /**
     * 将渲染后的 Word 2003 XML 文件内容替换到 docx 模板中,生成最终的 docx 文件
     * @param docxTemplate    原始的 docx 模板路径(由 XML 另存得来)
     * @param renderedXmlPath 渲染后的 XML 文件路径
     * @param outputDocx      输出 docx 文件路径
     */
    public static void convert(String docxTemplate, String renderedXmlPath, String outputDocx) throws IOException {
        // 读取渲染后的 XML 文件内容(Ja va 8 兼容)
        Path xmlPath = Paths.get(renderedXmlPath);
        byte[] xmlBytes = Files.readAllBytes(xmlPath);
        String renderedXml = new String(xmlBytes, StandardCharsets.UTF_8);

        // 创建临时目录存放解压后的文件
        Path tempDir = Files.createTempDirectory("docx");
        try (ZipInputStream zis = new ZipInputStream(new FileInputStream(docxTemplate))) {
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                File outFile = new File(tempDir.toFile(), entry.getName());
                if (entry.isDirectory()) {
                    outFile.mkdirs();
                } else {
                    outFile.getParentFile().mkdirs();
                    try (FileOutputStream fos = new FileOutputStream(outFile)) {
                        byte[] buffer = new byte[8192];
                        int len;
                        while ((len = zis.read(buffer)) != -1) {
                            fos.write(buffer, 0, len);
                        }
                    }
                }
                zis.closeEntry();
            }
        }

        // 替换 document.xml
        Path docXmlPath = tempDir.resolve("word/document.xml");
        Files.write(docXmlPath, renderedXml.getBytes(StandardCharsets.UTF_8));

        // 重新打包为 docx
        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outputDocx))) {
            Files.walk(tempDir).forEach(path -> {
                if (Files.isRegularFile(path)) {
                    String entryName = tempDir.relativize(path).toString().replace('\\', '/');
                    try {
                        zos.putNextEntry(new ZipEntry(entryName));
                        Files.copy(path, zos);
                        zos.closeEntry();
                    } catch (IOException e) {
                        throw new UncheckedIOException(e);
                    }
                }
            });
        } finally {
            // 清理临时目录
            Files.walk(tempDir)
                 .map(Path::toFile)
                 .forEach(File::delete);
        }
    }

    public static void main(String[] args) throws IOException {
        convert("G:\\templates\\template.docx", "G:\\templates\\output2.xml", "F:\\test2.docx");
        System.out.println("docx 文件已生成, haha ");
    }
}
来源:https://www.jb51.net/program/362217okn.htm
上一篇centos php环境搭建 下一篇centos中php-fpm如何设置超时时间
本站内容用于信息整理与展示,如有侵权或内容问题请及时联系处理。

相关推荐

补充同频道和同主题内容,方便继续浏览更多相关内容。

同类最新

继续查看同栏目最近更新的文章。

更多
详解如何使用Apache服务器进行防盗链配置步骤
编程语言 · 2026-06-30

详解如何使用Apache服务器进行防盗链配置步骤

Apache使用mod_rewrite模块实现图片防盗链,通过 htaccess文件配置Rewrite规则,检查HTTP_REFERER来源,若非本站域名且来源不为空,则对jpg等常见图片格式返回403禁止访问。此方法能有效阻止大多数盗链行为。

Filebeat日志转发实现步骤详解
编程语言 · 2026-06-30

Filebeat日志转发实现步骤详解

Filebeat通过配置输入源读取日志,输出目标转发至Elasticsearch或Logstash。安装后编辑filebeat yml文件,指定日志路径和输出地址。支持直接转发或经Logstash处理。通过systemctl启动并验证数据到达,可选SSL加密和多行日志合并配置。

手把手教你如何在CentOS上使用PhpStorm构建项目的详细步骤
编程语言 · 2026-06-30

手把手教你如何在CentOS上使用PhpStorm构建项目的详细步骤

在CentOS上使用PHPStorm构建项目需先准备环境:安装Java、PHP及扩展、Nginx、MariaDB并开放端口。然后安装配置PHPStorm,设置SSH解释器与Web服务器映射。导入或创建项目后安装Composer依赖,调整php ini。配置SFTP部署并同步文件,最后设置Xdebug进行调试运行。

CentOS下GitLab集成其他工具的详细配置方法与完整指南
编程语言 · 2026-06-30

CentOS下GitLab集成其他工具的详细配置方法与完整指南

在CentOS平台中,GitLab通过Webhooks、API与CI CD配置,深度集成Jenkins、SonarQube、Docker及Slack,构建代码托管、自动构建、质量检查与协作通知的自动化链路,覆盖开发、测试、部署全流程,实现从提交到上线的自动化,大幅提升团队效率与交付质量,推动开发运维一体化。

CentOS设置Node.js定时任务的方法
编程语言 · 2026-06-30

CentOS设置Node.js定时任务的方法

在CentOS上为Node js应用设置定时任务常用两种方案:systemd适合长期运行服务,需创建服务文件并配置开机自启;cron更灵活,适合定期唤醒任务,通过编辑crontab添加时间计划和执行命令。两种方法均需指定Node js路径和应用入口。