Java使用Poi填充Word表格模板(图片和文字)
**** 由于个人需求需要对表格模板进行操作,所以本文章只对表格进行替换数据操作,没有段落,没有循环遍历,没有延伸!!!!!(后续补充!!!)
**** 由于本人是个菜鸡,所以也查了很多"大佬"的方法,有的完全是照搬,有的还照搬不完全,稀里糊涂的扔一大堆。谢谢这些"大佬"们的分享。真是人逼人,逼死人。我xxx!!!!
**** 话不多说,上案例,直接复制可用,更换自己东西就行了。
测试类:
public void wordUtils() throws IOException, ParseException {
// 本地文件 自行更换
// 模板文件地址
String inputUrl = "src\\test\\resources\\DTAQZY3.docx";
// 新生产的模板文件
String outputUrl = "src\\test\\resources\\test2.docx";
// 图片地址
String imageUrl = "src\\main\\resources\\Xiong.jpg";
XWPFDocument document = WordUtils.inputDocument(inputUrl);
byte[] bs = WordUtils.getImageByteArray(imageUrl);
// model() 对应填充元素,自行填写 例如 dataMap.put("name","张三");
// model() 这个方法自己写!!!要不然就在测试类直接往紧塞!!! new 对象 .set 然后 .put 往紧塞!
Map<String, Object> dataMap = model();
// imageMap 填充单个图片元素集合,需与数据模型元素分开填充
// 多张图片请填充多个集合
Map<String, Object> imageMap = new HashMap<>();
imageMap.put("width", 700000);
imageMap.put("height", 700000); // 宽高设置尽量大些,底层沿用EMU计算
//EMU(英制公制单位)。1 EMU = 1/914400英寸= 1/36000 mm
String[] imageSplit = imageUrl.split("\\."); // 请根据各自的路径进行分割,反斜杠分割要写"\\\\"
// 可直接更换为文件名称后缀,后续会自行判断
imageMap.put("type", imageSplit[imageSplit.length - 1]);
imageMap.put("con", bs);
dataMap.put("image", imageMap);
// 处理文档数据
String s = WordUtils.parseDocument(document, dataMap);
System.out.println(s);
// 导出填充后文档
WordUtils.outputDocument(document, outputUrl);
}
工具类(再次提醒,目前我的需求只对表格替换数据操作,没有段落,没有循环遍历,没有延伸,都后续补充!!!):
package com.lsh.espimp.soms.process.test;
import fr.opensagres.xdocreport.core.io.IOUtils;
import org.apache.poi.ooxml.POIXMLDocument;
import org.apache.poi.xwpf.usermodel.*;
import java.io.*;
import java.util.*;
/**
* @author GPeng
* @description: WordUtils 手写 ---测试版
* @time 2022/11/09 14:58
**/
public class WordUtils {
/**
* @param inputFileUrl 模板读取路径
* @return org.apache.poi.xwpf.usermodel.XWPFDocument
* @description: 读取模板文件
* @author GPeng
* @time 2022/11/09 15:02
**/
public static XWPFDocument inputDocument(String inputFileUrl) throws IOException {
XWPFDocument document = new XWPFDocument(POIXMLDocument.open