我需要从文档中删除封面
XWPFDocument document = ...;
if(document.getBodyElements().get(0) instanceof XWPFSDT) {
document.removeBodyElement(0);
}
调试文档
时,XWPFSDT
元素已正确删除,但输出封面页仍位于此处。
是否有某种方法可以更新/刷新文档 xml,即使更改是从低级别发生的,我们如何刷新文档以使其保持最新
最佳答案
直到apache poi
版本3.17
,XWPFDocument.removeBodyElement仅正确删除 BodyElementType.TABLE
或 BodyElementType.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();
}
}
关于java - 刷新XWPF文档更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50761461/