首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用POI读/写具有完整POIFSFileSystem的文档

问使用POI读/写具有完整POIFSFileSystem的文档
EN

Stack Overflow用户
提问于 2018-12-27 15:57:03
回答 1查看 637关注 0票数 0

我有以下问题,就像每个人一样,我想用Word文档中的其他项目来替换一些项目。问题是,文档包含的页眉和页脚是POIFSFileSystem的一部分(我之所以知道这一点,是因为读取FS /将文档写回-without任何更改都会丢失这些信息,而读取FS /将其作为新文件写回不会丢失这些信息)。

目前我这样做:

代码语言:javascript
复制
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();

但是,此操作失败,并显示以下错误:

代码语言:javascript
复制
Opened read-only or via an InputStream, a Writeable File is required

如果我不重写文档,它可以正常工作,但我的更改会丢失。另一方面,如果我只保存文档,而不保存文件系统,则会丢失页眉/页脚。

现在的问题是,如何在“另存为”整个文件系统的同时更新文档,或者是否有一种方法可以强制文档包含文件系统中的所有内容?

EN

回答 1

Stack Overflow用户

发布于 2018-12-31 14:46:25

因为DOC二进制文件格式是所有H格式中最可怕的,所以HWPF内容总是在便签簿中。所以它真的还没有准备好,而且在很多情况下也会有be。

但在你的特殊情况下,你的观察是不可重现的。使用apache poi 4.0.1,在从*.doc文件创建之后,HWPFDocument包含页眉故事,也包含页脚故事。所以下面的方法对我来说是有效的:

来源:

​

​

代码:

代码语言:javascript
复制
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,就像我对我的代码所做的那样。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53941627

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档