我有一个 Microsoft Word .docx 文档上传到 Sharepoint。在我的 java 代码中,我已将此文档下载到一个 byte[] 中。好的。现在,我想要处理这个 byte[] 以获得 XWPFDocument 并能够将一些变量替换到文档中。
请问,有人能帮帮我吗?
谢谢!!
您可以使用 XWPFDocument 的构造函数中指定的 InputStream(ByteArrayInputStream) 从 byte[] 读取 XWPFDocument,并且可以从 XWPFDocument 中获取段落和运行。之后,您可以像下面这样进行编辑。
byte[] byteData = ....
// read as XWPFDocument from byte[]
XWPFDocument doc = new XWPFDocument(new ByteArrayInputStream(byteData));
int numberToPrint = 0;
// you can edit paragraphs
for (XWPFParagraph para : doc.getParagraphs()) {
List<XWPFRun> runs = para.getRuns();
numberToPrint++;
for (XWPFRun run : runs) {
// read text
String text = run.getText(0);
// edit text and update it
run.setText(numberToPrint + " " + text, 0);
}
}
// save it and you can get the updated .docx
FileOutputStream fos = new FileOutputStream(new File("updated.docx"));
doc.write(fos);
ByteArrayInputStream bis = new ByteArrayInputStream(bytebuffer);
POIXMLTextExtractor extractor = (POIXMLTextExtractor) ExtractorFactory.createExtractor(bis);
POIXMLDocument document = extractor.getDocument();
if (document instanceof XWPFDocument)
XWPFDocument xDocument = (XWPFDocument) document;