刷新XWPFDocument更改

时间:2018-06-08 13:14:05

标签: java apache-poi xwpf

我需要从文档中删除封面

XWPFDocument document = ...;

if(document.getBodyElements().get(0) instanceof XWPFSDT) {
    document.removeBodyElement(0);
}

调试document时,XWPFSDT元素已正确删除,但输出封面仍在此处。

有没有办法更新/刷新文档xml,即使从低级别发生更改,我们如何刷新文档以使其保持最新状态

1 个答案:

答案 0 :(得分:2)

apache poi版本3.17之前,XWPFDocument.removeBodyElement只能正确删除BodyElementType.TABLEBodyElementType.PARAGRAPH。它缺少CTBody.removeSdt

所以我们必须做自己的低级别事情:

import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.poi.xwpf.usermodel.*;

public class WordRemoveCoverPage {

 public static void main(String[] args) throws Exception {

  XWPFDocument document = new XWPFDocument(new FileInputStream("WordDocumentWithCoverPage.docx"));

  if(document.getBodyElements().get(0) instanceof XWPFSDT) {
   System.out.println(document.removeBodyElement(0)); // true == success, but low level <w:sdt> is not removed from the XML
   document.getDocument().getBody().removeSdt(0);
  }

  document.write(new FileOutputStream("WordDocumentWithoutCoverPage.docx"));

  document.close();
 }
}