gpt4 book ai didi

java - 如何从 byte[] 创建 XWPFDocument?

转载 作者:行者123 更新时间:2023-11-29 04:39:35 25 4
gpt4 key购买 nike

我有一个 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);

关于java - 如何从 byte[] 创建 XWPFDocument?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39770755/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com