用apache poi合并多个word并生成一个新word,现在遇到个问题,原word中有竖版有横版,怎么在合并时按原始word的排版保留原样式.
/**
* 多个word合并,按照文件顺序合并为一个word
*
* @param mergeFileName 指定合并后的目标文件名
* @param fileNames 指定所有需要合并的word文件名
*/
public static void mergeMultiWord(String mergeFileName, List<String> fileNames) {
try {
OutputStream dest = new FileOutputStream(mergeFileName);
ArrayList<XWPFDocument> documentList = new ArrayList<>();
XWPFDocument mergeDoc = null;
for (int i = 0; i < fileNames.size(); i++) {
FileInputStream in = new FileInputStream(fileNames.get(i));
OPCPackage open = OPCPackage.open(in);
XWPFDocument document = new XWPFDocument(open);
documentList.add(document);
}
for (int i = 0; i < documentList.size(); i++) {
mergeDoc = documentList.get(0);
XWPFDocument document = documentList.get(i);
if (i != documentList.size() - 1) {
// 最后一页不再设置分页符
document.createParagraph().setPageBreak(true);
}
if (i != 0) {
appendBody(mergeDoc, document);
}
}
mergeDoc.write(dest);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void appendBody(XWPFDocument src, XWPFDocument append) throws Exception {
CTBody src1Body = src.getDocument().getBody();
CTBody src2Body = append.getDocument().getBody();
List<XWPFPictureData> allPictures = append.getAllPictures();
Map<String, String> map = new HashMap<>();
for (XWPFPictureData picture : allPictures) {
String before = append.getRelationId(picture);
String after = src.addPictureData(picture.getData(), Document.PICTURE_TYPE_PNG);
map.put(before, after);
}
appendBody(src1Body, src2Body, map);
}
private static void appendBody(CTBody 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()) {
for (Map.Entry<String, String> set : map.entrySet()) {
addPart = addPart.replace(set.getKey(), set.getValue());
}
}
CTBody makeBody = CTBody.Factory.parse(prefix + mainPart + addPart + sufix);
src.set(makeBody);
}
以上是我现在的代码