package '折线图';

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.*;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class ExcelChartExample {

    public static void main(String[] args) {
        try {
            // 读取 Excel 文件
            FileInputStream fileIn = new FileInputStream("output.xlsx");
            XSSFWorkbook workbook = new XSSFWorkbook(fileIn);
            XSSFSheet sheet = workbook.getSheetAt(0);

            // 创建折线图
            XSSFDrawing drawing = sheet.createDrawingPatriarch();
            XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 4, 1, 10, 20);
            XSSFChart chart = drawing.createChart(anchor);
            chart.setTitleText("数据折线图");
            chart.setTitleOverlay(false);

            // 设置图例位置
            chart.getOrAddLegend().setPosition(LegendPosition.BOTTOM);

            // 创建数据系列
            XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
            XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT);
            leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);

            // 创建数据源
            XDDFNumericalDataSource<Double> xs = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(1, sheet.getLastRowNum(), 0, 0));
            XDDFNumericalDataSource<Double> ys = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(1, sheet.getLastRowNum(), 1, 1));

            // 添加数据系列
            XDDFLineChartData data = (XDDFLineChartData) chart.createData(ChartTypes.LINE, bottomAxis, leftAxis);
            XDDFLineChartData.Series series = (XDDFLineChartData.Series) data.addSeries(xs, ys);
            series.setTitle("数据折线图", null);

            // 绘制图表
            chart.plot(data);

            // 保存 Excel 文件
            FileOutputStream fileOut = new FileOutputStream("output.xlsx");
            workbook.write(fileOut);
            fileOut.close();

            System.out.println("折线图已创建并保存到 Excel 文件中。");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这段代码会读取名为“output.xlsx”的 Excel 文件,并在该文件中创建折线图。注意,这段代码假设 Excel 文件中已经存在数据,并且数据位于第一个工作表的第一列和第二列中。如果你的 Excel 文件的数据位置不同,需要相应地调整代码中的数据源范围。


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

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