Java 删除Word目录
本文以Java代码示例介绍如何删除Word中的目录。添加目录可参考之前写的这篇文章。
工具/材料
Word测试文档,版本.docx2013
Word jar包文件,free spire.doc.jar,版本3.9.0
Jdk版本1.8.0
IDEA编译环境,版本2018
操作方法
01、
在Java程序中引入jar包,如下图:
02、
在IDEA项目文件夹下存入需要用于测试的Word文档。
03、
在程序中键入如下代码内容:import com.spire.doc.*;import com.spire.doc.documents.Paragraph;public class RemoveTOC { public static void main(String[]args){ //加载包含目录的Word文档 Document doc = new Document(); doc.loadFromFile("sample.docx"); //获取section Section section = doc.getSections().get(0); //遍历段落 for (int i = 0; i < section.getParagraphs().getCount(); i++) { Paragraph paragraph = section.getParagraphs().get(i); if (paragraph.getStyleName().matches("TOC\\w+")) { section.getParagraphs().removeAt(i);//删除目录 i--; } } //保存文档 doc.saveToFile("RemoveTOC.docx", FileFormat.Docx_2013); doc.dispose(); }}
04、
执行程序,生成文档,如下图,
End
特别提示
文件路径可自定义。