原先实现了使用替换符号实现文字替换
链接:积累知识库:POI操作word文档实现替换符替换文字_poi替换word内容-优快云博客
现在又有新需求实现图片替换,只需要使用run.addPicture()这个api即可,稍作更改,代码如下:
实体添加图片参数:
@Data
@Builder
public class ReplaceParam {
//占位符
private String placeholder;
//替换值
private String replaceValue;
//默认值
private String defaultValue = "";
//文字大小
private Integer size;
//字体样式
private String fontFamily;
//字体颜色
private String color;
//是否图片
private Boolean isPicture = false;
//图片高度
private Integer height = 12;
//图片宽度
private Integer weight = 24;
//图片
private File pictureFile;
}
在遍历文档内容时候进行判断是否是图片:
@SneakyThrows
private static void changeValue(XWPFRun run, Map<String, ReplaceParam> replaceParamMap) {
Set<Map.Entry<String, ReplaceParam>> textSets = replaceParamMap.entrySet();
for (Map.Entry<String, ReplaceParam> textSet : textSets) {
//匹配模板与替换值 格式${key}
String key = textSet.getKey() ;
ReplaceParam replaceParam = textSet.getValue();
if (run.toString().contains(key)) {
if (replaceParam.getIsPicture() && replaceParam.getPictureFile() != null){
File pictureFile = replaceParam.getPictureFile();
FileInputStream fileInputStream = new FileInputStream(pictureFile);
//将替换符去掉
run.setText("",0);
run.addPicture(fileInputStream, XWPFDocument.PICTURE_TYPE_JPEG,
replaceParam.getPictureFile().getName(),
Units.toEMU(replaceParam.getWeight()),
Units.toEMU(replaceParam.getHeight()));
continue;
}
//替换值
String replaceValue = replaceParam.getReplaceValue() == null ? replaceParam.getDefaultValue() : replaceParam.getReplaceValue();
String value = run.toString().replace(key, replaceValue);
run.setText(value,0);
if (replaceParam.getSize() != null){
run.setFontSize(replaceParam.getSize());
}
if (replaceParam.getColor() != null){
run.setColor(replaceParam.getColor());
}
if (replaceParam.getFontFamily() != null){
run.setFontFamily(replaceParam.getFontFamily());
}
//...........................
}
}
}
实现结果: