Java 使用 Apache POI 库从 Excel 文件创建折线图
要实现你的要求,你可以使用 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.xssf.usermodel.*;
public class ExcelLineChartExample {
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();
// 设置横坐标轴
ChartAxis bottomAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM);
bottomAxis.setTitle('时间');
bottomAxis.setCrosses(AxisCrosses.AUTO_ZERO);
// 设置纵坐标轴
ValueAxis leftAxis = 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 库添加到你的项目依赖中。这段代码会读取名为 'input-1.xlsx' 的 Excel 文件中的 'P1' 工作表,并根据你的要求生成折线图,然后将结果保存回原始文件。
原文地址: https://www.cveoy.top/t/topic/fSy9 著作权归作者所有。请勿转载和采集!