SXSSFWorkbook支持图表吗?
时间: 2023-10-16 18:11:43 浏览: 128
是的,Apache POI中的SXSSFWorkbook支持插入图表。您可以使用以下代码示例将图表添加到工作簿中:
```java
// 创建工作簿
SXSSFWorkbook workbook = new SXSSFWorkbook();
// 创建工作表
Sheet sheet = workbook.createSheet("Chart Test");
// 创建图表数据
Row row;
Cell cell;
for (int i = 0; i < 5; i++) {
row = sheet.createRow(i);
cell = row.createCell(0);
cell.setCellValue("Category " + (i+1));
cell = row.createCell(1);
cell.setCellValue(new Random().nextInt(100));
}
// 创建图表
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 4, 0, 10, 15);
Chart chart = drawing.createChart(anchor);
// 创建数值轴
ValueAxis valueAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.BOTTOM);
valueAxis.setCrosses(AxisCrosses.AUTO_ZERO);
// 创建类别轴
CategoryAxis categoryAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.LEFT);
// 创建图表数据源
ChartDataSource<Number> xs = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(0, 4, 1, 1));
ChartDataSource<String> ys = DataSources.fromStringCellRange(sheet, new CellRangeAddress(0, 4, 0, 0));
// 创建折线图
LineChartData data = chart.getChartDataFactory().createLineChartData();
data.addSeries(xs, ys);
chart.plot(data, new ChartAxis[] { categoryAxis, valueAxis });
// 输出工作簿
workbook.write(new FileOutputStream("Chart.xlsx"));
workbook.close();
```
这段代码将在工作表“Chart Test”中创建一个包含5个分类和随机值的数据集,并将该数据集作为折线图插入到工作簿中。您可以根据需要调整图表的类型和位置。
阅读全文