Apache POI set Excel chart title

十年热恋 提交于 2020-01-22 19:29:45

问题


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?

来源:https://stackoverflow.com/questions/30532612/apache-poi-set-excel-chart-title

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!