How to Create Bulleted and Numbered Lists in a Word Document in Java
Aspose.Words FOSS for Java writes bulleted and numbered lists with the ListFormat of a DocumentBuilder. This guide writes one list of each kind, saves the document and counts the list items, with the library from Maven Central.
Step-by-Step Guide
Step 1: Install the Package
Add the package to your build. The library needs Java 8 or later.
<dependency>
<groupId>org.aspose</groupId>
<artifactId>aspose-words-foss</artifactId>
<version>26.3.0</version>
</dependency>Step 2: Import the Classes
All classes are in the com.aspose.words package, so the example starts with import com.aspose.words.*;.
Step 3: Start a Bulleted List
builder.getListFormat().applyBulletDefault() starts a default bulleted list; every paragraph written after it is an item.
Step 4: End It and Start a Numbered List
removeNumbers() ends the list, then applyNumberDefault() starts a default numbered one.
import com.aspose.words.*;
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.getListFormat().applyBulletDefault();
builder.writeln("Install the package");
builder.writeln("Write the code");
builder.getListFormat().removeNumbers();
builder.getListFormat().applyNumberDefault();
builder.writeln("First step");
builder.writeln("Second step");
builder.getListFormat().removeNumbers();
doc.save("lists.docx");
Document reloaded = new Document("lists.docx");
int items = 0;
NodeCollection paragraphs = reloaded.getChildNodes(NodeType.PARAGRAPH, true);
for (int i = 0; i < paragraphs.getCount(); i++) {
if (((Paragraph) paragraphs.get(i)).getListFormat().isListItem()) {
items++;
}
}
System.out.println("List items: " + items);
System.out.println("Lists in the document: " + reloaded.getLists().getCount());The program printed:
List items: 4
Lists in the document: 2Step 5: Save and Count
After saving and reloading, the example counted 4 paragraphs for which getListFormat().isListItem() is true, in 2 lists.
Common Issues and Fixes
Text after the list is numbered. The list was not ended. Call removeNumbers().
The compiler reports an unreported exception. The Document constructors, Document.save and some other methods declare throws Exception. Declare it on the calling method or catch it.
Frequently Asked Questions
How do I create a nested list?
Call listIndent() and listOutdent(), as in the Lists guide.
Can I use another bullet style?
Yes. ListCollection.add takes one of the ListTemplate constants, such as BULLET_DISK.