使用Apache POI创建Excel折线图
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xddf.usermodel.chart.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelChartExample04 {
public static void main(String[] args) {
String filePath = 'input-1.xlsx';
String sheetName = 'P1';
try {
// 读取Excel文件
FileInputStream file = new FileInputStream(filePath);
Workbook workbook = new XSSFWorkbook(file);
Sheet sheet = workbook.getSheet(sheetName);
// 创建折线图
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15);
Chart chart = drawing.createChart(anchor);
ChartLegend legend = chart.getOrCreateLegend();
legend.setPosition(LegendPosition.BOTTOM);
LineChartData data = chart.getChartDataFactory().createLineChartData();
// 设置横坐标轴
XDDFCategoryAxis bottomAxis = (XDDFCategoryAxis) chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM);
bottomAxis.setTitle('时间');
bottomAxis.setCrosses(AxisCrosses.AUTO_ZERO);
// 设置纵坐标轴
XDDFValueAxis leftAxis = (XDDFValueAxis) chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT);
leftAxis.setTitle('数值');
leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);
// 读取数据并添加到折线图中
Row row = sheet.getRow(0);
for (int i = 0; i < 127; i++) {
Cell xCell = row.getCell(i);
Cell yCell = sheet.getRow(2).getCell(i);
double xValue = xCell.getNumericCellValue();
double yValue = yCell.getNumericCellValue();
data.addSeries(
chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM),
chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT),
chart.getChartDataFactory().createCategoryDataSource(sheet, new CellRangeAddress(0, 0, i, i)),
chart.getChartDataFactory().createNumericDataSource(sheet, new CellRangeAddress(2, 2, i, i))
);
}
chart.plot(data, bottomAxis, leftAxis);
// 保存Excel文件
FileOutputStream outFile = new FileOutputStream(filePath);
workbook.write(outFile);
outFile.close();
System.out.println('折线图已生成并保存在P1工作表中。');
} catch (IOException e) {
e.printStackTrace();
}
}
}
代码解释:
这段代码使用Apache POI库在Excel文件中创建一个简单的折线图。
- 导入必要的类: 代码首先导入必要的类,包括处理Excel文件、创建图表和处理数据的类。
- 加载Excel文件: 代码加载指定的Excel文件和工作表。
- 创建图表对象: 代码创建一个
Chart对象,表示要创建的折线图。 - 设置图表图例: 代码设置图表的图例位置为底部。
- 创建图表数据: 代码创建
LineChartData对象,用于存储折线图的数据。 - 设置坐标轴: 代码设置横坐标轴和纵坐标轴的标题、刻度等属性。
- 添加数据系列: 代码循环读取数据,并将数据添加到图表的数据系列中。
- 绘制图表: 代码使用
plot方法将数据绘制到图表上。 - 保存Excel文件: 代码将修改后的Excel文件保存到磁盘。
这段代码演示了如何使用Apache POI库在Excel文件中创建简单的折线图。你可以根据自己的需要修改代码,例如更改图表类型、数据源、样式等。
原文地址: https://www.cveoy.top/t/topic/fSzd 著作权归作者所有。请勿转载和采集!