Java生成excel图表
时间: 2023-10-04 08:11:22 浏览: 85
Java可以使用Apache POI库来生成Excel图表。
以下是一个生成Excel柱状图的示例代码:
```java
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
public class ExcelChartExample {
public static void main(String[] args) throws Exception {
//创建工作簿
XSSFWorkbook workbook = new XSSFWorkbook();
//创建工作表
XSSFSheet sheet = workbook.createSheet("Chart");
//创建数据
Object[][] data = {
{"Month", "Sales"},
{"Jan", 100},
{"Feb", 200},
{"Mar", 300},
{"Apr", 400},
{"May", 500},
{"Jun", 600},
{"Jul", 700},
{"Aug", 800},
{"Sep", 900},
{"Oct", 1000},
{"Nov", 1100},
{"Dec", 1200}
};
//创建数据行
int rowCount = 0;
for (Object[] rowData : data) {
Row row = sheet.createRow(rowCount++);
int columnCount = 0;
for (Object field : rowData) {
Cell cell = row.createCell(columnCount++);
if (field instanceof String) {
cell.setCellValue((String) field);
} else if (field instanceof Integer) {
cell.setCellValue((Integer) field);
}
}
}
//创建柱状图
XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 5, 1, 15, 15);
XSSFChart chart = drawing.createChart(anchor);
chart.setTitleText("Sales Chart");
//设置数据源
XDDFDataSource<String> categories = XDDFDataSourcesFactory.fromStringCellRange(sheet, new CellRangeAddress(0, rowCount - 1, 0, 0));
XDDFNumericalDataSource<Double> values = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(0, rowCount - 1, 1, 1));
//创建柱状图数据
XDDFChartData chartData = chart.createData(ChartTypes.BAR, null, null);
chartData.setVaryColors(true);
XDDFChartData.Series series = chartData.addSeries(categories, values);
series.setTitle("Sales", null);
//设置坐标轴
XDDFCategoryAxis xAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
xAxis.setTitle("Month");
XDDFValueAxis yAxis = chart.createValueAxis(AxisPosition.LEFT);
yAxis.setTitle("Sales");
//绘制图表
chart.plot(chartData);
//保存工作簿
FileOutputStream outputStream = new FileOutputStream(new File("chart.xlsx"));
workbook.write(outputStream);
workbook.close();
}
}
```
该代码会生成一个包含柱状图的Excel文件。具体实现过程如下:
1. 创建工作簿和工作表;
2. 创建数据;
3. 创建数据行,并将数据填充进去;
4. 创建柱状图,并设置图表标题;
5. 设置数据源和坐标轴;
6. 创建柱状图数据,并设置柱状图颜色和标题;
7. 绘制图表;
8. 保存工作簿。
可以根据需要修改代码中的数据、图表类型等参数。
阅读全文