我有以下问题,就像每个人一样,我想用Word文档中的其他项目来替换一些项目。问题是,文档包含的页眉和页脚是POIFSFileSystem的一部分(我之所以知道这一点,是因为读取FS /将文档写回-without任何更改都会丢失这些信息,而读取FS /将其作为新文件写回不会丢失这些信息)。
目前我这样做:
POIFSFileSystem pfs = new POIFSFileSystem(fis);
HWPFDocument document = new HWPFDocument(pfs);
Range r1 = document.getRange();
…
document.write();
ByteArrayOutputStream bos = new ByteArrayOutputStream(50000);
pfs.writeFilesystem(bos);
pfs.close();但是,此操作失败,并显示以下错误:
Opened read-only or via an InputStream, a Writeable File is required如果我不重写文档,它可以正常工作,但我的更改会丢失。另一方面,如果我只保存文档,而不保存文件系统,则会丢失页眉/页脚。
现在的问题是,如何在“另存为”整个文件系统的同时更新文档,或者是否有一种方法可以强制文档包含文件系统中的所有内容?
发布于 2018-12-31 14:46:25
因为DOC二进制文件格式是所有H格式中最可怕的,所以HWPF内容总是在便签簿中。所以它真的还没有准备好,而且在很多情况下也会有be。
但在你的特殊情况下,你的观察是不可重现的。使用apache poi 4.0.1,在从*.doc文件创建之后,HWPFDocument包含页眉故事,也包含页脚故事。所以下面的方法对我来说是有效的:
来源:

代码:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.hwpf.*;
import org.apache.poi.hwpf.usermodel.*;
public class ReadAndWriteDOCWithHeaderFooter {
public static void main(String[] args) throws Exception {
HWPFDocument document = new HWPFDocument(new FileInputStream("TemplateDOCWithHeaderFooter.doc"));
Range bodyRange = document.getRange();
System.out.println(bodyRange);
for (int p = 0; p < bodyRange.numParagraphs(); p++) {
System.out.println(bodyRange.getParagraph(p).text());
if (bodyRange.getParagraph(p).text().contains("<<NAME>>"))
bodyRange.getParagraph(p).replaceText("<<NAME>>", "Axel Richter");
if (bodyRange.getParagraph(p).text().contains("<<DATE>>"))
bodyRange.getParagraph(p).replaceText("<<DATE>>", "12/21/1964");
if (bodyRange.getParagraph(p).text().contains("<<AMOUNT>>"))
bodyRange.getParagraph(p).replaceText("<<AMOUNT>>", "1,234.56");
System.out.println(bodyRange.getParagraph(p).text());
}
System.out.println("==============================================================================");
Range overallRange = document.getOverallRange();
System.out.println(overallRange);
for (int p = 0; p < overallRange.numParagraphs(); p++) {
System.out.println(overallRange.getParagraph(p).text()); // contains all inclusive header and footer
}
FileOutputStream out = new FileOutputStream("ResultDOCWithHeaderFooter.doc");
document.write(out);
out.close();
document.close();
}
}结果:

所以请再检查一遍,告诉我们到底是什么对你不起作用。因为我们需要重现它,请提供一个minimal, complete, and verifiable example,就像我对我的代码所做的那样。
https://stackoverflow.com/questions/53941627
复制相似问题