java 使用免费版spire.doc.free:5.2.0生成doc文件中1~3级目录 完整代码
时间: 2023-09-03 10:15:03 浏览: 72
以下是使用Spire.Doc.Free生成doc文件并添加1~3级目录的Java代码示例:
```java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;
public class GenerateDocWithTOC {
public static void main(String[] args) {
// 创建一个新的Word文档
Document doc = new Document();
// 添加标题
Paragraph title = doc.addSection().addParagraph();
TextRange titleText = title.appendText("这是一个示例文档");
titleText.getCharacterFormat().setBold(true);
titleText.getCharacterFormat().setTextSize(18f);
titleText.getCharacterFormat().setTextColor(Color.BLUE);
title.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
// 添加正文内容
Section section = doc.addSection();
Paragraph para1 = section.addParagraph();
TextRange text1 = para1.appendText("这是第一段落");
Paragraph para2 = section.addParagraph();
TextRange text2 = para2.appendText("这是第二段落");
Paragraph para3 = section.addParagraph();
TextRange text3 = para3.appendText("这是第三段落");
// 添加目录
Paragraph tocTitle = doc.addParagraph();
TextRange tocTitleText = tocTitle.appendText("目录");
tocTitleText.getCharacterFormat().setBold(true);
tocTitleText.getCharacterFormat().setTextSize(14f);
tocTitleText.getCharacterFormat().setTextColor(Color.BLACK);
// 设置目录样式
doc.getStyles().get("Normal").getParagraphFormat().setStyleName("TOC 1");
doc.getStyles().get("Heading 1").getParagraphFormat().setStyleName("TOC 2");
doc.getStyles().get("Heading 2").getParagraphFormat().setStyleName("TOC 3");
// 添加目录域
Paragraph toc = doc.addParagraph();
Field tocField = toc.appendField("TOC", FieldType.Field_Toc);
TocFieldSettings tocSettings = new TocFieldSettings();
tocSettings.setIncludePageNumbers(true);
tocSettings.setLowerHeadingLevel(1);
tocSettings.setUpperHeadingLevel(3);
tocField.setFieldSettings(tocSettings);
// 保存文档
doc.saveToFile("GenerateDocWithTOC.docx", FileFormat.Docx);
}
}
```
这个示例代码将会创建一个包含标题、正文内容和目录的Word文档,并将1~3级标题自动添加到目录中。你可以根据需要自定义样式和设置。注意,Spire.Doc.Free只支持doc和docx格式,因此在保存文档时需要指定文件格式。