需求:根据固定的word模板进行数据填充生成word
具体代码:
try {
//获取文件操作对象 inputStream word模板的输入流
XWPFDocument document = new XWPFDocument(inputStream);
//获取段落迭代器
Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();
String text;
Set<String> set;
XWPFParagraph paragraph;
List<XWPFRun> run;
String key;
nextTime:
//判断是否还有段落
while (itPara.hasNext()) {
//获取段落元素
paragraph = itPara.next();
//这个map中 我设置的是对象要取的属性值和要替换的word模板的字符
set = map.keySet();
//获取列集合
run = paragraph.getRuns();
if (run.size() < 1) {
continue nextTime;
}
Iterator<String> iterator = set.iterator();
while (iterator.hasNext()) {
key = iterator.next();
//循环列的值
for (int i = 0, runSie = run.size(); i < runSie; i++) {
XWPFRun xwpfRun = run.get(i);
//得到当前列的元素文本
text = xwpfRun.getText(xwpfRun.getTextPosition());
int i1 = text.indexOf(key);
//如果当前元素文本是要替换的字符
if (text != null && i1 > -1) {
//进行文本替换
xwpfRun.setText(text.replace(key, String.valueOf(map.get(key))), 0);
}
}
}
XWPFRun xwpfRun = run.get(0);
String erWeiMaIndexText = xwpfRun.getText(xwpfRun.getTextPosition());
if (erWeiMaIndexText != null && erWeiMaIndexText.equals("ERWEIMA")) {
java.io.File file1 = QRcodeGenerator.from(ServletUtils.getFullContextPath(request) + "/service/rest/tk.File/" + fileId + "/view").file();
FileInputStream fileInputStream = new FileInputStream(file1);
BufferedImage read = ImageIO.read(file1);
//设置图片,fileInputStream图片输入流,类型,名称,宽,高
xwpfRun.addPicture(fileInputStream, Document.PICTURE_TYPE_PNG, file1.getName(), Units.pixelToEMU(100), Units.pixelToEMU(100));
xwpfRun.setText(" ", 0);
}
if (erWeiMaIndexText != null && erWeiMaIndexText.equals("CURRENTTIME")) {
xwpfRun.setText(DateUtil.formatDate(new Date(), "yyyy年MM月dd日"), 0);
}
}
//写入文件outputStream
document.write(outputStream);
} finally {
//关闭流
outputStream.close();
inputStream.close();
}