Apache POI柱状图负数值柱体无颜色问题求助
解决Apache POI柱状图负值柱体无颜色问题
问题根源在于Apache POI的高层XDDF API默认未处理负值柱体的填充配置,需通过底层XML对象显式设置正负值柱体的填充规则,确保负值柱体正常显示颜色。
修改后的完整代码如下:
public class BarChart2 { public static void main(String[] args) throws Exception { try (XSSFWorkbook wb = new XSSFWorkbook()) { String sheetName = "test"; XSSFSheet sheet = wb.createSheet(sheetName); // 创建数据行 Row row = sheet.createRow((short) 0); Cell cell = row.createCell((short) 0); cell.setCellValue("Jan"); cell = row.createCell((short) 1); cell.setCellValue(23); row = sheet.createRow((short) 1); cell = row.createCell((short) 0); cell.setCellValue("Feb"); cell = row.createCell((short) 1); cell.setCellValue(-5); row = sheet.createRow((short) 2); cell = row.createCell((short) 0); cell.setCellValue("March"); cell = row.createCell((short) 1); cell.setCellValue(15); XSSFDrawing drawing = sheet.createDrawingPatriarch(); XSSFClientAnchor anchor = drawing.createAnchor(5, 5, 5, 5, 5, 0, 12, 20); XSSFChart chart = drawing.createChart(anchor); chart.setTitleText("Report" ); chart.setTitleOverlay(false); XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM); bottomAxis.setTitle("Month"); XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT); leftAxis.setTitle("Area"); leftAxis.setCrosses(AxisCrosses.AUTO_ZERO); XDDFDataSource<String> months = XDDFDataSourcesFactory.fromStringCellRange(sheet, new CellRangeAddress(0, 2, 0, 0)); XDDFNumericalDataSource<Double> values = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(0, 2, 1, 1)); XDDFBarChartData data = (XDDFBarChartData) chart.createData(ChartTypes.BAR, bottomAxis, leftAxis); XDDFBarChartData.Series series1 = (XDDFBarChartData.Series) data.addSeries(months, values); series1.setTitle("Month", null); data.setVaryColors(false); chart.plot(data); data.setBarDirection(BarDirection.COL); // 核心配置:设置正负值柱体颜色 CTBarSer ctBarSer = series1.getXmlObject(); // 设置正值柱体填充色(示例:深绿色) CTSolidFill positiveFill = ctBarSer.getSpPr().addNewSolidFill(); positiveFill.addNewSrgbClr().setVal(new byte[]{(byte)0x2E, (byte)0x7D, (byte)0x32}); // 开启负值颜色反转,并设置负值柱体填充色(示例:深红色) ctBarSer.addNewInvertIfNegative().setVal(true); CTColor negativeColor = CTColor.Factory.newInstance(); negativeColor.addNewSrgbClr().setVal(new byte[]{(byte)0xC6, (byte)0x28, (byte)0x28}); ctBarSer.addNewNegativeColor().setVal(negativeColor); // 写入文件 String filename = "test.xlsx"; try (FileOutputStream fileOut = new FileOutputStream("C:\\"+filename)) { wb.write(fileOut); } } } }
关键修改说明:
- 直接转换图表数据类型:将
chart.createData结果转为XDDFBarChartData,避免后续强制转换的冗余操作。 - 底层XML对象控制:通过
series1.getXmlObject()获取CTBarSer,这是控制柱状图系列样式的核心底层结构。 - 正负值颜色分离配置:
- 为正值柱体设置实心填充色
- 开启
InvertIfNegative规则,并单独指定负值柱体的填充颜色
修改后,负值柱体将正常显示为指定颜色,不会再出现空柱情况。
内容的提问来源于stack exchange,提问作者Anil Jagtap
相关产品推荐
相关产品推荐

