当前位置:首页 > 后端开发 > 正文

Java如何生成Word文档?

在Java中导出Word文档,通常使用Apache POI库操作.docx文件或Freemarker模板引擎生成,也可选择Docx4j或iText等工具,需注意处理格式兼容性和性能优化,具体实现需结合文档复杂度选择方案。

Apache POI方案(原生操作,灵活性强)

原理:通过Java API直接操作Word文档结构
适用场景:动态生成复杂格式文档(表格、图片、样式调整)
步骤

  1. 添加Maven依赖:

    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>5.2.3</version>
    </dependency>
  2. 基础代码示例(生成.docx):

    import org.apache.poi.xwpf.usermodel.*;
    public class PoiExport {
      public static void main(String[] args) throws Exception {
        // 1. 创建文档对象
        XWPFDocument doc = new XWPFDocument();
        // 2. 添加标题
        XWPFParagraph title = doc.createParagraph();
        title.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun titleRun = title.createRun();
        titleRun.setText("用户报告");
        titleRun.setBold(true);
        titleRun.setFontSize(16);
        // 3. 添加表格(2行3列)
        XWPFTable table = doc.createTable(2, 3);
        table.getRow(0).getCell(0).setText("姓名");
        table.getRow(0).getCell(1).setText("年龄");
        table.getRow(0).getCell(2).setText("职业");
        table.getRow(1).getCell(0).setText("张三");
        table.getRow(1).getCell(1).setText("28");
        table.getRow(1).getCell(2).setText("工程师");
        // 4. 输出文件
        FileOutputStream out = new FileOutputStream("report.docx");
        doc.write(out);
        out.close();
      }
    }

    优点:精细控制文档元素
    缺点:代码量大,样式需手动配置

    Java如何生成Word文档?  第1张


Freemarker模板方案(数据驱动,高效批处理)

原理:将Word文档转为XML模板,动态填充数据
适用场景:固定格式文档批量生成(如合同、证书)
步骤

  1. 准备模板文件:

    • 用Word创建模板并另存为 XML文件(.ftl)
    • 在占位符使用 ${variable} 语法(如 ${userName}
  2. 添加依赖:

    <dependency>
      <groupId>org.freemarker</groupId>
      <artifactId>freemarker</artifactId>
      <version>2.3.32</version>
    </dependency>
  3. Java处理代码:

    import freemarker.template.Configuration;
    import freemarker.template.Template;
    import java.io.*;
    import java.util.HashMap;
    import java.util.Map;
    public class FtlExport {
      public static void main(String[] args) throws Exception {
        // 1. 配置模板目录
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_32);
        cfg.setDirectoryForTemplateLoading(new File("/templates"));
        // 2. 加载模板文件
        Template template = cfg.getTemplate("contract.ftl");
        // 3. 准备动态数据
        Map<String, Object> data = new HashMap<>();
        data.put("userName", "李四");
        data.put("signDate", "2025-10-15");
        // 4. 生成Word文档
        FileOutputStream out = new FileOutputStream("contract.docx");
        Writer writer = new OutputStreamWriter(out, "UTF-8");
        template.process(data, writer);
        writer.close();
      }
    }

优点:解耦设计与代码,维护简单
缺点:复杂样式需调整XML结构


iText RTF方案(轻量级文本导出)

原理:通过RTF格式生成基础Word文档
适用场景:纯文本内容快速导出(无需复杂格式)
代码片段

import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.rtf.RtfWriter2;
public class RtfExport {
  public static void main(String[] args) throws Exception {
    Document doc = new Document();
    RtfWriter2.getInstance(doc, new FileOutputStream("output.rtf"));
    doc.open();
    doc.add(new Paragraph("简易报告内容"));
    doc.close();
  }
}

注意:RTF兼容性有限,非.docx标准格式


方案对比与选型建议

方案 适用场景 开发效率 格式支持
Apache POI 动态复杂文档
Freemarker 模板化批量生成
iText (RTF) 纯文本快速导出 极高

推荐选择

  • 企业级应用:优先用 Freemarker(维护成本低)
  • 高度定制化需求:选择 Apache POI(灵活性高)
  • 避免处理旧版.doc格式(POI对doc支持不完善)

避坑指南

  1. 中文乱码
    • POI设置字体:run.setFontFamily("宋体")
    • Freemarker模板用UTF-8编码
  2. 文档损坏
    确保操作完成后调用doc.close()out.close()
  3. 性能优化
    批量导出时用SXSSFWorkbook(POI流式API)

引用说明

  • Apache POI官方文档:https://poi.apache.org/
  • Freemarker手册:https://freemarker.apache.org/
  • 微软OpenXML标准:ECMA-376
    本文代码基于JDK 1.8验证,请确保使用推荐依赖版本
0