How to Insert a Chart Into a Word Document in Java
Aspose.Words FOSS for Java inserts charts into Word documents with DocumentBuilder.insertChart. This guide inserts a column chart with one data series and a title and reads it back, 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: Insert the Chart
insertChart(ChartType.COLUMN, 432, 252) inserts a column chart 432 by 252 points and returns the Shape that holds it.
Step 4: Set the Series and the Title
Clear the sample series with getSeries().clear(), add yours with add(name, categories, values) and set the title with getTitle().setText.
import com.aspose.words.*;
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Shape shape = builder.insertChart(ChartType.COLUMN, 432, 252);
Chart chart = shape.getChart();
chart.getSeries().clear();
chart.getSeries().add("Revenue", new String[] {"Q1", "Q2", "Q3"}, new double[] {120, 150, 180});
chart.getTitle().setText("Revenue by quarter");
doc.save("chart.docx");
Document reloaded = new Document("chart.docx");
Shape saved = null;
NodeCollection shapes = reloaded.getChildNodes(NodeType.SHAPE, true);
for (int i = 0; i < shapes.getCount(); i++) {
Shape candidate = (Shape) shapes.get(i);
if (candidate.hasChart()) {
saved = candidate;
}
}
Chart savedChart = saved.getChart();
System.out.println("Chart title: " + savedChart.getTitle().getText());
System.out.println("Series: " + savedChart.getSeries().getCount());
System.out.println("Series name: " + savedChart.getSeries().get(0).getName());The program printed:
Chart title: Revenue by quarter
Series: 1
Series name: RevenueStep 5: Save and Read It Back
After saving and reloading, the shape with hasChart() true had the title Revenue by quarter and 1 series named Revenue.
Common Issues and Fixes
Chart.setStyle throws a NullPointerException. It did on a chart created with insertChart in a test on Java 8, 17 and 21. Do not call it on such a chart.
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
Can I render the chart as an image?
No. Saving to image and fixed-page formats is rejected in this edition.
How do I find charts in an existing document?
Loop over getChildNodes(NodeType.SHAPE, true) and check hasChart().