JAVA使用XWPFDocument进行段落替换,分段异常解决方案
public static void changeParagraph(XWPFDocument document, Map<String, Object> textMap) {
List<XWPFParagraph> paragraphs = document.getParagraphs();
for (XWPFParagraph paragraph : paragraphs) {
List<XWPFRun> runs = paragraph.getRuns();
for (XWPFRun run : runs) {
String text = run.getText(0);
if (checkText(text)) {
for (Map.Entry<String, Object> entry : textMap.entrySet()) {
String key = "${" + entry.getKey() + "}";
Object value = entry.getValue();
if (text.contains(key)) {
if (value instanceof String) {
text = text.replace(key, (String) value);
} else if (value instanceof Map) {
text = text.replace(key, "");
Map picMap = (Map) value;
int width = Integer.parseInt(picMap.get("width").toString());
int height = Integer.parseInt(picMap.get("height").toString());
int picType = getPictureType(picMap.get("type").toString());
byte[] byteArray = (byte[]) picMap.get("content");
ByteArrayInputStream byteInputStream = new ByteArrayInputStream(byteArray);
try {
String blipId = document.addPictureData(byteInputStream, picType);
int id = document.getNextPicNameNumber(picType);
XWPFUtils.createPicture(id, blipId, width, height, run);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
run.setText(text, 0);
}
}
}
}