Apache POI set Excel chart title

2019-04-08 06:23发布

I'm creating an Excel workbook from scratch. One of the sheets contains a chart, and I want to set the chart title.

Apache POI has a setChartTitle method on HSSFChart, but neither XSSFChart nor the format-agnostic Chart have methods to set the chart title. Since I need to create .xlsx files this is a problem for me.

After much poking around in POI code and OOXML specifications I managed to come up with this code for setting the title on a newly created Chart:

    if (chart instanceof XSSFChart) {
        XSSFChart xchart = (XSSFChart) chart;
        CTChart ctChart = xchart.getCTChart();
        CTTitle title = ctChart.addNewTitle();
        CTTx tx = title.addNewTx();
        CTTextBody rich = tx.addNewRich();
        rich.addNewBodyPr();  // body properties must exist, but can be empty
        CTTextParagraph para = rich.addNewP();
        CTRegularTextRun r = para.addNewR();
        r.setT("My chart title");
    }

This seems to work - I can load the resulting file in Excel 2013 and the chart is there with the correct title.

Is there an easier way to do this? What gotchas would I need to look out for when changing a chart title in a workbook created in Excel?

0条回答
登录 后发表回答