poi导出柱状图的代码
时间: 2023-07-02 22:05:52 浏览: 138
下面是使用Apache POI库导出柱状图的示例代码:
```java
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
public class BarChartExample {
public static void main(String[] args) throws Exception {
//创建工作簿
Workbook workbook = new XSSFWorkbook();
//创建工作表
Sheet sheet = workbook.createSheet("Bar Chart Example");
//定义数据
Object[][] data = {
{"Month", "Sales"},
{"January", 100},
{"February", 120},
{"March", 80},
{"April", 90},
{"May", 110},
{"June", 130},
{"July", 70},
{"August", 90},
{"September", 100},
{"October", 120},
{"November", 80},
{"December", 90}
};
//创建行和单元格,并填充数据
int rowNum = 0;
for (Object[] rowData : data) {
Row row = sheet.createRow(rowNum++);
int colNum = 0;
for (Object field : rowData) {
Cell cell = row.createCell(colNum++);
if (field instanceof String) {
cell.setCellValue((String) field);
} else if (field instanceof Integer) {
cell.setCellValue((Integer) field);
}
}
}
//创建柱状图
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 5, 1, 15, 20);
Chart chart = drawing.createChart(anchor);
//设置图表类型和标题
ChartLegend legend = chart.getOrCreateLegend();
legend.setPosition(LegendPosition.TOP_RIGHT);
BarChartData dataChart = chart.getChartDataFactory().createBarChartData();
ChartAxis bottomAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM);
ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT);
leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);
ChartDataSource<Number> xs = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 12, 1, 1));
ChartDataSource<Number> ys1 = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 12, 2, 2));
dataChart.addSeries(xs, ys1);
chart.plot(dataChart, bottomAxis, leftAxis);
//保存工作簿到文件
FileOutputStream fileOut = new FileOutputStream("bar-chart-example.xlsx");
workbook.write(fileOut);
fileOut.close();
System.out.println("The bar chart has been exported to bar-chart-example.xlsx");
}
}
```
这个示例代码会创建一个柱状图,并将其导出到名为“bar-chart-example.xlsx”的Excel文件中。可以根据需要修改数据、图表类型、图表位置等。
阅读全文