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.AxisCrosses;
import org.apache.poi.xddf.usermodel.chart.AxisPosition;
import org.apache.poi.xddf.usermodel.chart.LegendPosition;
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();

            // 设置横坐标轴
            org.apache.poi.xddf.usermodel.chart.XDDFChartAxis bottomAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM);
            bottomAxis.setTitle('时间');
            bottomAxis.setCrosses(AxisCrosses.AUTO_ZERO);

            // 设置纵坐标轴
            org.apache.poi.xddf.usermodel.chart.XDDFValueAxis 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创建Excel折线图教程

原文地址: https://www.cveoy.top/t/topic/lai2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录