Home » excel » java – Problem running official examples LineChars and ScatterChart with Apache POI 4.0

java – Problem running official examples LineChars and ScatterChart with Apache POI 4.0

Posted by: admin April 23, 2020 Leave a comment

Questions:

There’s a problem with the official examples LineChart and ScatterChart for Apache POI 4.0. They compile and run without errors, but the created Excel file cannot be opened stating that there is unreadable content. Excel 2010 & 2016 are giving the option to recover data from the workbook and after clickin’ yes, this dialog appears. What might be the problem?

How to&Answers:

The new XDDF code lacks the setting the axIds in the lineChart and scatterChart.

In /xl/charts/chart1.xml this looks like:

<c:lineChart>
 ...
 <c:axId val="0"/>
 <c:axId val="1"/>
</c:lineChart>

for a line chart..

Do adding:

...
            XDDFChartData data = chart.createData(ChartTypes.LINE, bottomAxis, leftAxis);
            data.addSeries(xs, ys1);
            data.addSeries(xs, ys2);
            chart.plot(data);

            //setting the axis Ids to the LineChart
            chart.getCTChart().getPlotArea().getLineChartArray(0).addNewAxId().setVal(bottomAxis.getId());
            chart.getCTChart().getPlotArea().getLineChartArray(0).addNewAxId().setVal(leftAxis.getId());


            // Write the output to a file
            try (FileOutputStream fileOut = new FileOutputStream("ooxml-line-chart.xlsx")) {
                wb.write(fileOut);
            }
...

in LineChart.java

and

...
            XDDFChartData data = chart.createData(ChartTypes.SCATTER, bottomAxis, leftAxis);

            data.addSeries(xs, ys1);
            data.addSeries(xs, ys2);
            chart.plot(data);

            //setting the axis Ids to the ScatterChart
            chart.getCTChart().getPlotArea().getScatterChartArray(0).addNewAxId().setVal(bottomAxis.getId());
            chart.getCTChart().getPlotArea().getScatterChartArray(0).addNewAxId().setVal(leftAxis.getId());


            // Write the output to a file
            try (FileOutputStream fileOut = new FileOutputStream("ooxml-scatter-chart.xlsx")) {
                wb.write(fileOut);
            }

...

in ScatterChart.java

and it will work.