当前位置: 首页 > news >正文

Java使用Apache POI向Word文档中填充数据

Java使用Apache POI向Word文档中填充数据

向一个包含占位符的Word文档中填充数据,并保存为新的文档。

准备工作
  1. 环境搭建

    • 在项目中添加Apache POI依赖。在pom.xml中添加如下依赖:

      <dependencies><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>5.2.2</version> <!-- 请检查最新的版本号 --></dependency>
      </dependencies>
      
  2. 准备Word文档

    • 创建一个.docx文件作为模板。在这个文档中,需要定义一些占位符,例如{{name}}{{age}}等。这些占位符将在程序运行时被替换为实际的数据。
编写代码
  1. 导入必要的包

    import org.apache.poi.xwpf.usermodel.XWPFDocument;
    import org.apache.poi.xwpf.usermodel.XWPFParagraph;
    import org.apache.poi.xwpf.usermodel.XWPFRun;import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.util.List;
    
  2. 创建主类和方法

    public class WordFiller {public static void main(String[] args) {try {fillDocumentWithValues();} catch (Exception e) {e.printStackTrace();}}private static void fillDocumentWithValues() throws Exception {// 1. 加载现有的Word文档FileInputStream fis = new FileInputStream(new File("template.docx"));XWPFDocument document = new XWPFDocument(fis);// 2. 遍历文档中的所有段落List<XWPFParagraph> paragraphs = document.getParagraphs();for (XWPFParagraph paragraph : paragraphs) {// 3. 遍历每个段落中的所有runList<XWPFRun> runs = paragraph.getRuns();if (runs != null) {for (XWPFRun run : runs) {// 4. 获取文本并替换占位符String text = run.getText(0);if (text != null) {text = text.replaceAll("\\{\\{name\\}\\}", "John Doe");text = text.replaceAll("\\{\\{age\\}\\}", "30");run.setText(text, 0);}}}}// 5. 将修改后的文档保存到新的文件FileOutputStream out = new FileOutputStream("filled-document.docx");document.write(out);// 6. 关闭所有打开的资源out.close();fis.close();document.close();}
    }
    
复杂文档的处理
1. 加载文档

首先,加载Word文档。

FileInputStream fis = new FileInputStream(new File("complex-template.docx"));
XWPFDocument document = new XWPFDocument(fis);
2. 替换文本

对于简单文本的替换,前面的示例已经涵盖了基本方法。对于复杂的文档,可能需要根据不同的情况来决定如何替换文本。

3. 处理表格

如果文档中包含表格,可以使用XWPFTable类来操作表格。

// 获取文档中的所有表格
List<XWPFTable> tables = document.getTables();for (XWPFTable table : tables) {// 遍历表格中的每一行for (int i = 0; i < table.getNumberOfRows(); i++) {XWPFTableRow row = table.getRow(i);// 遍历行中的每一列for (int j = 0; j < row.getTableCells().size(); j++) {XWPFTableCell cell = row.getCell(j);// 获取单元格中的所有段落List<XWPFParagraph> paragraphs = cell.getParagraphs();for (XWPFParagraph paragraph : paragraphs) {// 替换单元格中的文本List<XWPFRun> runs = paragraph.getRuns();if (runs != null) {for (XWPFRun run : runs) {String text = run.getText(0);if (text != null) {text = text.replaceAll("\\{\\{name\\}\\}", "John Doe");text = text.replaceAll("\\{\\{age\\}\\}", "30");run.setText(text, 0);}}}}}}
}
4. 添加/删除表格行或列

可以通过XWPFTable的方法来添加或删除行和列。

XWPFTable table = tables.get(0); // 获取第一个表格
XWPFTableRow newRow = table.createRow(); // 添加新行
newRow.createCell().setText("New Column"); // 添加新列,并设置文本
5. 插入图片

使用XWPFPictureData类来插入图片。

File imgFile = new File("path/to/image.png");
FileInputStream fisImg = new FileInputStream(imgFile);
byte[] bytes = new byte[(int) imgFile.length()];
fisImg.read(bytes);XWPFParagraph para = document.createParagraph();
XWPFRun run = para.createRun();
run.addPicture(bytes, XWPFDocument.PICTURE_TYPE_PNG, "image.png", Units.toEMU(150), Units.toEMU(150));
6. 设置样式

可以通过XWPFStyle来设置文档的样式。

XWPFStyle style = document.createStyle();
style.setStyleName("MyStyle");
style.setType(XWPFStyle.STYLE_TYPE.CHARACTER);
style.setFontFamily("Arial");// 应用样式
XWPFParagraph para = document.createParagraph();
para.getStyle().setStyleName("MyStyle");
7. 处理页眉和页脚

页眉和页脚也是可以通过XWPFHeaderXWPFFooter来访问和修改的。

XWPFHeader header = document.getDocument().getBody().getHeaders().get(0);
XWPFParagraph headerPara = header.createParagraph();
headerPara.createRun().setText("This is the header");
8. 保存文档

最后,记得保存文档。

FileOutputStream out = new FileOutputStream("output.docx");
document.write(out);
out.close();
document.close();

总结

处理复杂文档时,需要根据文档的具体内容来确定需要处理哪些元素。Apache POI提供了丰富的API来操作Word文档的各种组成部分。通过组合使用这些API,可以实现对文档的全面控制,从而满足各种复杂的需求。务必注意,处理大型文档时,内存管理变得非常重要,因为加载整个文档到内存可能会消耗大量的资源。在处理完毕后,及时关闭流和文档对象是很重要的。

http://www.lryc.cn/news/434772.html

相关文章:

  • Gitflow基础知识
  • NLP基础及其代码-tokenizer
  • OpenCV结构分析与形状描述符(8)点集凸包计算函数convexHull()的使用
  • 灰光模块,彩光模块-介绍
  • python-新冠病毒
  • 2023年408真题计算机网络篇
  • 分类学习器(Classification Learner App)MATLAB
  • DolphinDB 基准性能测试工具:金融模拟数据生成模块合集
  • BUUCTF—[BJDCTF2020]The mystery of ip
  • leecode100题-双指针-三数之和
  • 计算机毕业设计PySpark+Django考研分数线预测 考研院校推荐系统 考研推荐系统 考研爬虫 考研大数据 Hadoop 大数据毕设 机器学习 深度学习
  • Go语言多态实践以及gin框架c.BindJSON序列化遇到的坑
  • SpringCloud神领物流学习笔记:项目概述(一)
  • RocketMQ异步报错:No route info of this topic
  • Node.js学习记录(一)
  • 【AI】Pytorch_模型构建
  • FFmpeg源码:avcodec_descriptor_get函数分析
  • 为数据仓库构建Zero-ETL无缝集成数据分析方案(下篇)
  • ElMessageBox消息确认框组件在使用时如何设置第三个或多个自定义按钮
  • javaWeb【day04】--(MavenSpringBootWeb入门)
  • [Linux]:文件(下)
  • 【学习笔记】手写Tomcat 一
  • springboot基础-Druid数据库连接池使用
  • C语言文件操作全攻略:从打开fopen到读写r,w,一网打尽
  • 【0328】Postgres内核之 “User ID state”
  • VisualStudio环境搭建C++
  • linux 文件压缩并且切割压缩
  • 支持iPhone 16新品预售,饿了么同步上线专人配送等特色服务
  • 低光增强效果展示
  • 李诞-2021.8脱口秀工作手册-11-pitch your idea把一个想法扎进别人脑子里;专业,做足准备,给选择option!