使用Apache POI创建Excel折线图
package 折线图;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xddf.usermodel.*;
import org.apache.poi.xddf.usermodel.chart.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
public class ExcelChartExample {
public static void main(String[] args) {
try {
// 创建工作簿和工作表
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet('折线图');
// 创建数据行和列
Row row = sheet.createRow(0);
row.createCell(0).setCellValue('X');
row.createCell(1).setCellValue('Y');
// 填充数据
for (int i = 1; i <= 10; i++) {
row = sheet.createRow(i);
row.createCell(0).setCellValue(i);
row.createCell(1).setCellValue(i * i);
}
// 创建折线图
Drawing<?> drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 4, 1, 10, 20);
Chart chart = drawing.createChart(anchor);
chart.setTitleText('数据折线图');
chart.setTitleOverlay(false);
// 设置图例位置
chart.getOrAddLegend().setPosition(LegendPosition.BOTTOM);
// 创建数据系列
LineChartData data = chart.getChartDataFactory().createLineChartData();
ChartAxis bottomAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM);
ChartAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT);
leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);
// 创建数据源
ChartDataSource<Number> xs = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 10, 0, 0));
ChartDataSource<Number> ys = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 10, 1, 1));
// 添加数据系列
LineChartSeries series = data.addSeries(xs, ys);
series.setTitle('数据折线图');
// 绘制图表
chart.plot(data, bottomAxis, leftAxis);
// 保存Excel文件
FileOutputStream fileOut = new FileOutputStream('output.xlsx');
workbook.write(fileOut);
fileOut.close();
System.out.println('折线图已创建并保存到Excel文件中。');
} catch (IOException e) {
e.printStackTrace();
}
}
}
原文地址: https://www.cveoy.top/t/topic/f3K6 著作权归作者所有。请勿转载和采集!