对于现有文档(含标题),使用spire.doc去生成目录,由于不是免费版,没有表格行数限制,但第一页开头有个版权声明,只需要用spire生成目录,然后用poi打开它删去第一行声明即可。
spire依赖
</dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc</artifactId>
<version>3.7.2</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>com.e-iceblue</id>
<url>https://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
示例
import com.spire.doc.Document;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import java.io.*;
@Controller
public class SpireDocController {
private static final String path = "D:\\";
@GetMapping("/export_word4")
public String userCenter4() throws IOException {
//打开Word文档
Document doc = new Document(path + "\\template.docx");
doc.getSections().get(0).getParagraphs().get(0).appendTOC(1,3);
//更新目录
doc.updateTableOfContents();
doc.saveToFile(path + "\\output.docx");
InputStream is = new FileInputStream(path + "\\output.docx");
XWPFDocument document = new XWPFDocument(is);
//以上Spire.Doc 生成的文件会自带警告信息,这里来删除Spire.Doc 的警告
document.removeBodyElement(0);
//输出word内容文件
OutputStream out = new FileOutputStream(path + "\\output.docx");
document.write(out);
document.close();
out.close();
return "success";
}
}