如何将段落包括字符样式复制到apache poi中的新文档?



我试图将一定数量的段落从ms word文件复制到Apache Poi的新文件中。虽然我没有问题地复制段落样式,但我不能将内联字符样式转移到新文件,如何获取和应用字符样式到新的新文档?

FileInputStream in = new FileInputStream("oldDoc.docx");
XWPFDocument doc = new XWPFDocument(in);
XWPFDocument newDoc = new XWPFDocument();
// Copy styles from old to new doc
XWPFStyles newStyles = newDoc.createStyles();
newStyles.setStyles(doc.getStyle());
List<XWPFParagraph> paragraphs = doc.getParagraphs();
for (int p = 0; p < paragraphs.size(); p++) {
XWPFParagraph oldPar = paragraphs.get(p);
XWPFParagraph newPar = newDoc.createParagraph();
// Apply paragraph style
newPar.setStyle(oldPar.getStyle());
XWPFRun run = newPar.createRun();
run.setText(oldPar.getText());
}
FileOutputStream outNewDoc = new FileOutputStream("newDoc.docx");
newDoc.write(outNewDoc);
in.close();
outNewDoc.close();
try {
FileInputStream in = new FileInputStream("in.docx");
XWPFDocument oldDoc = new XWPFDocument(in);
XWPFDocument newDoc = new XWPFDocument();

// Copy styles from template to new doc
XWPFStyles newXStyles = newDoc.createStyles();
newXStyles.setStyles(oldDoc.getStyle());
List<XWPFParagraph> oldDocParagraphs = oldDoc.getParagraphs();
for (XWPFParagraph oldPar : oldDocParagraphs) {
// Create new paragraph and set it style of old paragraph
XWPFParagraph newPar = newDoc.createParagraph();
newPar.setStyle(oldPar.getStyle());
// Loop in runs of old paragraphs.
for (XWPFRun oldRun : oldPar.getRuns()) { // Paragrafın sitillere göre parçalanmış stringleri
// Create a run for the new paragraph
XWPFRun newParRun = newPar.createRun();
// Set old run's text of old paragraph to the run of new paragraph
String runText = oldRun.text();
newParRun.setText(runText);
// Set old run's style of old paragraph to the run of new paragraph
CTRPr oldCTRPr = oldRun.getCTR().getRPr();
if (oldCTRPr != null) {
if (oldCTRPr.sizeOfRStyleArray() != 0){
String carStyle = oldRun.getStyle();
newParRun.setStyle(carStyle);
}
}
// Add the new run to the new paragraph
newPar.addRun(newParRun);
}
// Write to file and close.
FileOutputStream out = new FileOutputStream("out.docx");
newDoc.write(out);
out.close();
}
} catch (IOException | XmlException e) {
e.printStackTrace();
}

相关内容

  • 没有找到相关文章

最新更新