需求:生成Excel时支持图表,包括折线图、柱状图、条形图、饼状图、散点图、面积图。
要求:1、开源免费;2、支持跨平台
设计:
1. 使用图片代替Excel中的图表,采用JFreeChart渲染生成图表图片。
2. 采用POI操作Excel。
以下是向Excel2003文件生成折线图的示例(先用JFreeChart生成图片,再用POI将图片加入Excel文件):
效果图:
public static void test() throws Exception {
// 第一步,使用JFreeChart生成折线图的图片
// 图表标题、图表x轴名称、图表y轴名称
String title = "水果时间段销量";
String categoryAxisLabel = "时间";
String valueAxisLabel = "销量";
String[] titles = new String[] { title, categoryAxisLabel, valueAxisLabel };
String[] rowKeys = { "苹果", "橘子", "香蕉" };
String[] colKeys = { "10:00", "11:00", "12:00" };
double[][] data = { { 120, 200, 150 }, { 230, 200, 235 }, { 100, 200, 300 } };
byte[] bytes = LineChartImg.getBytes(titles, 400, 200, rowKeys, colKeys, data);
// 第二步,使用POI将图片放入excel文件
String excel = "F:/Users/zyj/Desktop/2019-09-27 自由报表/生成的报表.xls";
int[] anchors = new int[] { 0, 0, 0, 0, 2, 1, 12, 15 };
XlsHelper.addPicture(excel, 0, anchors, bytes);
}
部分maven:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.jfree</groupId>
<artifactId>jfreechart</artifactId>
<version>1.5.0</version>
</dependency>
使用JFreeChart生成折线图: