首页 > 知识问答文章正文

Java 删除Word目录

知识问答 2022-02-14 14:18:39 admin

本文以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】

执行程序,生成文档,如下图,

特别提示

文件路径可自定义。

标签:

发表评论

评论列表

可盼网Copyright @ 2011-2024 All Rights Reserved. |版权所有 备案号: 豫ICP备2022006457号-8