word文档任意位置拼接,支持段落、表格、图片。
/**
* 合并Word内容
*
* @param src
* @param append
* @throws Exception
*/
public static void appendBody(CTBody src, CTBody append) {
XmlOptions optionsOuter = new XmlOptions();
optionsOuter.setSaveOuter();
String appendString = append.xmlText(optionsOuter);
String srcString = src.xmlText();
String prefix = srcString.substring(0, srcString.indexOf(">") + 1);
String mainPart = srcString.substring(srcString.indexOf(">") + 1, srcString.lastIndexOf("<"));
String sufix = srcString.substring(srcString.lastIndexOf("<"));
String addPart = appendString.substring(appendString.indexOf(">") + 1, appendString.lastIndexOf("<"));
CTBody makeBody = null;
try {
makeBody = CTBody.Factory.parse(prefix + mainPart + addPart + sufix);
} catch (XmlException e) {
e.printStackTrace();
}
src.set(makeBody);
}
/**
* 段落拼接word,把文件中的图片拿出来
*
* @param src
* @param append
* @throws Exception
*/
public static void appendBody(XWPFParagraph xwpfParagraph, XWPFDocument append) throws Exception {
CTP ctp = xwpfParagraph.getCTP();
CTBody src2Body = append.getDocument().getBody();
List<XWPFPictureData> allPictures = append.getAllPictures();
// 记录图片合并前及合并后的ID
Map<String, String> map = new HashMap<>();
for (XWPFPictureData picture : allPictures) {
String before = append.getRelationId(picture);
//将原文档中的图片加入到目标文档中
String after = xwpfParagraph.getDocument().addPictureData(picture.getData(), Document.PICTURE_TYPE_PNG);
map.put(before, after);
}
appendBody(ctp, src2Body, map);
}
/**
* 把图片ID替换一下 避免冲突
*
* @param src
* @param append
* @param map
* @throws Exception
*/
private static void appendBody(CTP src, CTBody append, Map<String, String> map) throws Exception {
XmlOptions optionsOuter = new XmlOptions();
optionsOuter.setSaveOuter();
String appendString = append.xmlText(optionsOuter);
String srcString = src.xmlText();
String prefix = srcString.substring(0, srcString.indexOf(">") + 1);
String mainPart = srcString.substring(srcString.indexOf(">") + 1, srcString.lastIndexOf("<"));
String sufix = srcString.substring(srcString.lastIndexOf("<"));
String addPart = appendString.substring(appendString.indexOf(">") + 1, appendString.lastIndexOf("<"));
if (map != null && !map.isEmpty()) {
//对xml字符串中图片ID进行替换 z
// 下面注释掉的方式会发生图片id冲突
// for (Map.Entry<String, String> set : map.entrySet()) {
// addPart = addPart.replace(set.getKey(), "RE:"+set.getValue());
// }
// addPart = addPart.replaceAll("RE:",");
// 采用正则追加替换方式完美解决
String patter = StringUtils.join(map.keySet(), "|");
Pattern compile = Pattern.compile(patter);
Matcher matcher = compile.matcher(addPart);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
String value = map.get(matcher.group());
if (value != null) {
matcher.appendReplacement(sb, value);
}
}
matcher.appendTail(sb);
addPart = sb.toString();
}
//将两个文档的xml内容进行拼接
CTBody makeBody = CTBody.Factory.parse(prefix + mainPart + addPart + sufix);
src.set(makeBody);
}