Java 使用 Apache POI 从 Excel 文件创建折线图
您可以使用 Apache POI 库来读取 Excel 文件并创建折线图。以下是一个示例代码:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class ExcelChartExample {
public static void main(String[] args) {
String inputFile = 'input-1.xlsx';
try (Workbook workbook = WorkbookFactory.create(new FileInputStream(inputFile))) {
Sheet sheet = workbook.getSheet('P1');
// 创建图表数据源
int startRow = 0;
int endRow = 127;
int xAxisColumn = 0;
int yAxisColumn = 2;
ChartDataSource<Number> xData = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(startRow, endRow, xAxisColumn, xAxisColumn));
ChartDataSource<Number> yData = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(startRow, endRow, yAxisColumn, yAxisColumn));
// 创建折线图
Drawing<?> drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 4, 1, 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);
ChartAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT);
leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);
data.addSeries(xData, yData).setTitle('折线图');
// 设置横坐标轴格式为时间
bottomAxis.setNumberFormat('yyyy-MM-dd');
bottomAxis.setOrientation(AxisOrientation.MIN_MAX);
// 设置坐标轴标签
bottomAxis.setTitle('时间');
leftAxis.setTitle('数值');
// 将图表添加到工作表
chart.plot(data, bottomAxis, leftAxis);
// 保存 Excel 文件
try (FileOutputStream fileOut = new FileOutputStream(inputFile)) {
workbook.write(fileOut);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
请确保您已经添加了 Apache POI 库的依赖。该示例假设您的 Excel 文件已经存在,并且已经包含了 'P1' 工作表。如果您的 Excel 文件中没有 'P1' 工作表,您需要根据实际情况调整代码中的工作表名称。
此代码将创建一个折线图,将 A1-A127 作为横坐标轴,将 C1-C127 作为竖坐标轴,并将折线图保存在工作表中。横坐标轴将按照时间格式进行显示,例如 'yyyy-MM-dd'。您可以根据需要调整代码中的坐标轴范围、数据源和其他设置。
原文地址: https://www.cveoy.top/t/topic/fSy3 著作权归作者所有。请勿转载和采集!