刷新 XWPFDocument 更改

refresh XWPFDocument changes

我需要从文档中删除封面

XWPFDocument document = ...;

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

调试时 document XWPFSDT 元素被正确移除,但在输出封面上仍然存在。

有什么方法可以 update/refresh 记录 xml,即使更改是从低级别发生的,我们如何刷新文档以使其保持最新状态

直到apache poi版本3.17XWPFDocument.removeBodyElement removes only BodyElementType.TABLE or BodyElementType.PARAGRAPH properly. It lacks 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();
 }
}