java excel 饼图_Java 在 Excel 中创建饼图/环形图
时间: 2024-06-08 16:10:59 浏览: 252
Java 可以使用 Apache POI 库来操作 Excel 文件,其中也包括创建饼图和环形图。
以下是一个简单的示例代码,可以创建一个包含饼图的 Excel 文件:
```
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
public class PieChartExample {
public static void main(String[] args) throws Exception {
// 创建 Excel 文件
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Pie Chart");
// 创建数据行
Row row;
Cell cell;
row = sheet.createRow(0);
cell = row.createCell(0);
cell.setCellValue("Category");
cell = row.createCell(1);
cell.setCellValue("Value");
row = sheet.createRow(1);
cell = row.createCell(0);
cell.setCellValue("Apples");
cell = row.createCell(1);
cell.setCellValue(20);
row = sheet.createRow(2);
cell = row.createCell(0);
cell.setCellValue("Oranges");
cell = row.createCell(1);
cell.setCellValue(30);
row = sheet.createRow(3);
cell = row.createCell(0);
cell.setCellValue("Pears");
cell = row.createCell(1);
cell.setCellValue(10);
row = sheet.createRow(4);
cell = row.createCell(0);
cell.setCellValue("Bananas");
cell = row.createCell(1);
cell.setCellValue(40);
// 创建饼图
XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 5, 1, 15, 15);
XSSFChart chart = drawing.createChart(anchor);
chart.setTitleText("Fruit Sales");
chart.setTitleOverlay(false);
XDDFChartLegend legend = chart.getOrAddLegend();
legend.setPosition(org.apache.poi.xddf.usermodel.chart.LegendPosition.TOP_RIGHT);
XDDFDataSource<String> categories = XDDFDataSourcesFactory.fromStringCellRange(sheet, new CellRangeAddress(1, 4, 0, 0));
XDDFNumericalDataSource<Double> values = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(1, 4, 1, 1));
XDDFChartData data = chart.createData(ChartTypes.PIE, null, null);
data.setVaryColors(true);
data.addSeries(categories, values);
chart.plot(data);
// 保存文件
FileOutputStream fileOut = new FileOutputStream("PieChartExample.xlsx");
workbook.write(fileOut);
fileOut.close();
workbook.close();
}
}
```
这个示例代码创建了一个 Excel 文件,包含一个名为 "Pie Chart" 的工作表,该工作表包含一个简单的数据表格和一个饼图。你可以根据需要修改数据和图表的设置来满足你的需求。
阅读全文