Apache POI是Java生态中处理Office文档的核心工具,支持Excel图表的动态生成与数据绑定。本文以POI 5.x版本为例,详解如何在Excel中创建折线图、柱状图、饼图等常见图表,并提供代码示例与最佳实践。
一、环境配置与依赖管理
使用POI生成图表需引入以下核心依赖(以Maven为例):
xml
XML
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
注意:POI 5.x版本与旧版本(如3.x)API差异较大,需避免依赖冲突
二、数据源准备与工作表构建
- 创建工作簿与工作表
ini
Java
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("数据表");
- 填充数据
以国家GDP数据为例,首行写入国家名称,后续行填充数值:
scss
Java
// 创建标题行
Row headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("国家");
headerRow.createCell(1).setCellValue("俄罗斯");
headerRow.createCell(2).setCellValue("中国");
// 填充数据行
Row dataRow = sheet.createRow(1);
dataRow.createCell(0).setCellValue("GDP(万亿美元)");
dataRow.createCell(1).setCellValue(1.78);
dataRow.createCell(2).setCellValue(17.96);
三、图表生成核心步骤
1. 折线图(Line Chart)
ini
Java
// 定义图表位置与尺寸
XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 20);
// 创建图表对象
XSSFChart chart = drawing.createChart(anchor);
chart.setTitleText("国家GDP趋势分析");
// 绑定数据源
XDDFDataSource<String> countries = XDDFDataSourcesFactory.fromStringCellRange(sheet, new CellRangeAddress(0, 0, 1, 2));
XDDFNumericalDataSource<Double> values = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 1, 2));
// 配置坐标轴与样式
XDDFCategoryAxis xAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
XDDFValueAxis yAxis = chart.createValueAxis(AxisPosition.LEFT);
XDDFLineChartData data = (XDDFLineChartData) chart.createData(ChartTypes.LINE, xAxis, yAxis);
// 添加数据系列并渲染
XDDFLineChartData.Series series = data.addSeries(countries, values);
series.setTitle("GDP", null);
chart.plot(data);
关键点 :通过CellRangeAddress
绑定数据区域,支持动态扩展
2. 柱状图(Bar Chart)
柱状图与折线图代码结构类似,仅需修改图表类型与样式:
ini
Java
XDDFBarChartData data = (XDDFBarChartData) chart.createData(ChartTypes.BAR, xAxis, yAxis);
可通过XDDFShapeProperties
自定义柱体颜色与间距
3. 饼图(Pie Chart)
饼图需单独设置数据标签与百分比显示:
scss
Java
XDDFPieChartData data = (XDDFPieChartData) chart.createData(ChartTypes.PIE, null, null);
XDDFPieChartData.Series series = data.addSeries(countries, values);
chart.plot(data);
// 启用百分比标签
chart.getCTChart().getPlotArea().getPieChartArray(0).addNewDLbls().addNewShowPercent().setVal(true);
四、常见问题与优化
-
图表位置偏移
通过
XSSFClientAnchor
参数调整坐标(如col1, row1, col2, row2
)控制图表位置 -
数据动态更新
使用
CellRangeAddress
动态扩展数据范围,避免硬编码。例如:
ini
Java
CellRangeAddress valuesRange = new CellRangeAddress(1, 1, 1, sheet.getRow(1).getLastCellNum());
- 样式自定义
-
坐标轴标题 :
xAxis.setTitle("国家")
-
图例位置 :
chart.getOrAddLegend().setPosition(LegendPosition.TOP_RIGHT)
-
颜色设置 :通过
XDDFSolidFillProperties
指定RGB值
五、总结
通过POI生成Excel图表的核心在于数据绑定 与API灵活调用。开发者需注意:
- 数据区域需与图表类型匹配(如分类轴与数值轴);
- 高版本POI(≥5.0)推荐使用
XDDF
系列API,兼容性更强; - 复杂图表建议封装工具类(如
ChartUtils
)提升代码复用性