欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 游戏 > Java使用Apache POI向Word文档中填充数据

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

2024/10/25 1:22:18 来源:https://blog.csdn.net/weixin_42564451/article/details/142104976  浏览:    关键词: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,可以实现对文档的全面控制,从而满足各种复杂的需求。务必注意,处理大型文档时,内存管理变得非常重要,因为加载整个文档到内存可能会消耗大量的资源。在处理完毕后,及时关闭流和文档对象是很重要的。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com