首页 > 解决方案 > Apache POI 4 - 创建带有多个空单元格的 LINE 图表

问题描述

我确实喜欢基于我的数据源创建折线图,但不幸的是,当折线图 y 系列跨多个单元格时,它在绘图聊天时遇到 NullPointException。

我发现该列为空白时发生错误,并强制设置“0”以使其工作。

无论如何,我可以在没有硬编码“0”的空单元格上绘制图表?

下面是我如何硬编码默认值的方式,

for (int i = 0; headers.size() > i; i++) {
    row.createCell(i, CellType.NUMERIC);
}

下面是线图代码:

int rows = numberOfRows - 1;
int cols = headers.size();

XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15);
XSSFChart chart = drawing.createChart(anchor);
chart.displayBlanksAs(DisplayBlanks.GAP);

XDDFChartLegend legend = chart.getOrAddLegend();
legend.setPosition(LegendPosition.TOP_RIGHT);

// Use a category axis for the bottom axis.
XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
bottomAxis.setOrientation(AxisOrientation.MAX_MIN);
bottomAxis.setTitle("Date");

XDDFValueAxis rightAxis = chart.createValueAxis(AxisPosition.RIGHT);
rightAxis.setTitle("Rates");
rightAxis.setCrosses(AxisCrosses.AUTO_ZERO);

XDDFChartLegend chartLegend = chart.getOrAddLegend();
chartLegend.setPosition(LegendPosition.TOP_RIGHT);
chartLegend.setOverlay(false);

XDDFLineChartData lineChartData = (XDDFLineChartData) chart.createData(ChartTypes.LINE, bottomAxis, rightAxis);
lineChartData.setVaryColors(false);

XDDFDataSource<String> xs = XDDFDataSourcesFactory.fromStringCellRange(sheet, new CellRangeAddress(1, rows, 1, 1));

for (int col = 2; cols > col; col++) {
    XDDFNumericalDataSource<Double> ys = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(1, rows, col, col));
    XDDFLineChartData.Series series = (XDDFLineChartData.Series) lineChartData.addSeries(xs, ys);
    series.setTitle(headers.get(col), null);
    series.setSmooth(false);
    series.setMarkerStyle(MarkerStyle.NONE);
}

chart.plot(lineChartData);

标签: javaapache-poi

解决方案


推荐阅读