<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>org.apache.poi.xwpf.converter.pdf</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.10.1</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>org.apache.poi.xwpf.converter.pdf</artifactId>
<version>1.0.4</version>
</dependency>
/**
* 利用模板生成word文档
* @param filedValueMap 对应的字段 key - value 形式, 如果value是 inputstream 我们认为是图片, 并且是png的, 否则都会转成string
* @param inputStream 模板输入流
* @param outputStream 输出流
* @throws IOException
* @throws InvalidFormatException
*/
public static void POIUtilsTemplate2Word(Map<String, Object> filedValueMap, InputStream inputStream, OutputStream outputStream)
throws IOException, InvalidFormatException {
final XWPFDocument document = new XWPFDocument(inputStream).getXWPFDocument();
List<XWPFParagraph> paragraphList = document.getParagraphs();
List<String> filedList = Lists.newArrayList();
List<String> valueList = Lists.newArrayList();
List<String> filedInputStream = Lists.newArrayList();
List<Object> valueInputStream = Lists.newArrayList();
filedValueMap.forEach((filed, value) -> {
final String filedKey = String.format("${%s}", filed);
if (value instanceof InputStream) {
filedInputStream.add(filedKey);
valueInputStream.add(value);
} else {
filedList.add(filedKey);
valueList.add(String.valueOf(value));
}
});
final String[] filedArray = filedList.toArray(new String[filedList.size()]);
final String[] valueArray = valueList.toArray(new String[valueList.size()]);
for (XWPFParagraph paragraph : paragraphList) {
final List<XWPFRun> runs = paragraph.getRuns();
final String text = paragraph.getText();
String runText = StringUtils.replaceEach(text, filedArray, valueArray);
if (CollectionUtils.size(runs) > 0) {
// 为了 解决 POI 中 runs 分段错误问题, 他大爷的
for (int i = 0; i < runs.size(); i ++) {
// 是否包含图片
final int index = StringUtils.indexOfAny(text, filedInputStream.toArray(new String[filedInputStream.size()]));
if (index > -1 && i == 0) {
final XWPFRun run = runs.get(i);
/**
* 修改sonar问题,这个for循环只循环一次,所以直接取第一个 2020/06/05
*/
run.addPicture((InputStream) valueInputStream.get(0), HSSFPicture.PICTURE_TYPE_PNG, "file",
Units.toEMU(100), Units.toEMU(50));
// for (int filedIndex = 0; filedIndex < filedInputStream.size(); filedIndex++)
// {
// run.addPicture((InputStream) valueInputStream.get(filedIndex),
// HSSFPicture.PICTURE_TYPE_PNG,
// "file", Units.toEMU(100), Units.toEMU(50));
// break;
// }
} else {
runs.get(i).setText(i == 0 ? runText : "", 0);
}
}
}
}
document.write(outputStream);
}