Headings in Word can be quickly set using the options in “Styles” (Figure 1),
(figure 1)
When adding a directory, you can set the “effective Style” to be displayed at the “directory level” (Figure 2), and to some extent, the title outline can also be referenced as a directory.
(figure 2)
This article will show you how to get title content in Word through back-end Java program code.
** Note: ** This method can also be used to get a directory if the Settings shown in Figure 2 are made in Word; If there is no setting, the contents of the directory you want to retrieve by this method may be incomplete.
The Word document for this test is as shown in the figure below. [Title Style] and [Catalog level] have been set accordingly, and when obtaining the title outline, it is equivalent to obtaining the catalog:
(figure 3)
Code test environment:
- Word test document:.docx version 2013
- Compilation environment: IntelliJ IDEA 2018
- Jdk version: 1.8.0
- Word jar package: Free spire.doc.jar 3.9.0
Java program code
import com.spire.doc.*; import com.spire.doc.documents.Paragraph; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; Public class GetTitle {public static void main(String[] args)throws IOException {// Load Word test Document Document doc = new Document(); doc.loadFromFile("sample.docx"); File File = new File(" gettitle.txt "); if (file.exists()) { file.delete(); } file.createNewFile(); FileWriter fw = new FileWriter(file, true); BufferedWriter bw = new BufferedWriter(fw); // section for (int I = 0; i < doc.getSections().getCount(); i++) { Section section = doc.getSections().get(i); Paragraph for (int j = 0; j < section.getParagraphs().getCount(); j++) { Paragraph paragraph = section.getParagraphs().get(j); String text = text.gettext (); String text = text.gettext (); // Write text to TXT file bw.write(" title 1: "+ text + "\r"); String text = text.gettext ();} String text = text.gettext (); // Write text to TXT file bw.write(" title 2: "+ text + "\r"); String text = text.gettext ();} String text = text.getStylename ().matches("3"); // Write text to TXT file bw.write(" title 3: "+ text+"\r"); String text = text.gettext ();} String text = text.getStylename ().matches("4"); // Write text to TXT file bw.write(" title 4: "+ text+"\r"); } bw.write("\n"); } } bw.flush(); bw.close(); fw.close(); }}Copy the code
Title (table of Contents) get results:
Original content, reproduced please indicate the source!!