Java POI 创建 Excel 折线图教程

本教程将引导您使用 Apache POI 库在 Excel 文件中创建折线图。

1. 准备工作

  • 确保您已将 Apache POI 库添加到您的项目中。您可以从 https://poi.apache.org/ 下载。
  • 准备一个包含您想要在图表中显示的数据的 Excel 文件。

2. 代码示例

以下代码示例演示了如何使用 POI 库创建一个简单的折线图:

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;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ExcelChartExample05 {

    public static void main(String[] args) {
        try {
            // 读取 Excel 文件
            FileInputStream fileIn = new FileInputStream('input.xlsx');
            XSSFWorkbook workbook = new XSSFWorkbook(fileIn);
            XSSFSheet sheet1 = workbook.getSheet('P1');

            // 创建折线图
            XSSFDrawing drawing = sheet1.createDrawingPatriarch();
            XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 3, 9, 9, 19);
            XSSFChart chart = drawing.createChart(anchor);
            chart.setTitleText('数据折线图');
            chart.setTitleOverlay(false);

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

            // 设置横坐标轴为日期坐标轴
            XDDFDateAxis bottomAxis = chart.createDateAxis(AxisPosition.BOTTOM);
            bottomAxis.setCrosses(AxisCrosses.AUTO_ZERO);
            bottomAxis.setTitle('时间');

            // 设置时间格式
            SimpleDateFormat dateFormat = new SimpleDateFormat('yyyy-MM-dd');
            for (int i = 1; i <= 66; i++) {
                XSSFRow row = sheet1.getRow(i);
                if (row != null) {
                    Cell cell = row.getCell(0);
                    if (cell != null && cell.getCellType() == CellType.NUMERIC) {
                        Date date = cell.getDateCellValue();
                        String formattedDate = dateFormat.format(date);
                        bottomAxis.setTickLabelPosition(AxisTickLabelPosition.NEXT_TO);
                    }
                }
            }

            // 设置纵坐标轴
            XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT);
            leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);
            leftAxis.setTitle('数据值');

            // 设置次要纵坐标轴
            XDDFValueAxis rightAxis = chart.createValueAxis(AxisPosition.RIGHT);
            rightAxis.setCrosses(AxisCrosses.MAX);
            rightAxis.setTitle('次要数据值');

            // 设置数据源
            XDDFNumericalDataSource<Double> xs1 = XDDFDataSourcesFactory.fromNumericCellRange(sheet1, new CellRangeAddress(1, 66, 0, 0));
            XDDFNumericalDataSource<Double> ys1 = XDDFDataSourcesFactory.fromNumericCellRange(sheet1, new CellRangeAddress(1, 66, 1, 1));
            XDDFNumericalDataSource<Double> ys2 = XDDFDataSourcesFactory.fromNumericCellRange(sheet1, new CellRangeAddress(1, 66, 2, 2));
            XDDFNumericalDataSource<Double> ys3 = XDDFDataSourcesFactory.fromNumericCellRange(sheet1, new CellRangeAddress(1, 66, 2, 2));

            // 添加数据系列
            XDDFLineChartData data = (XDDFLineChartData) chart.createData(ChartTypes.LINE, bottomAxis, leftAxis);
            XDDFLineChartData.Series series1 = (XDDFLineChartData.Series) data.addSeries(xs1, ys1);
            series1.setTitle('P1数据折线图', null);
            series1.setSmooth(false);
            series1.setMarkerStyle(MarkerStyle.CIRCLE);
            XDDFLineChartData.Series series2 = (XDDFLineChartData.Series) data.addSeries(xs1, ys2);
            series2.setTitle('P1数据折线图', null);
            series2.setSmooth(false);
            series2.setMarkerStyle(MarkerStyle.CIRCLE);

            // 添加次要数据系列
            XDDFLineChartData.Series series3 = (XDDFLineChartData.Series) data.addSeries(xs1, ys3);
            series3.setTitle('次要数据折线图', null);
            series3.setSmooth(false);
            series3.setMarkerStyle(MarkerStyle.CIRCLE);
            chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(2).addNewSerAxId().setVal(rightAxis.getId());
            chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(2).getSerAxIdArray(0).setVal(leftAxis.getId());

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

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

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

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

3. 代码解释

  • 首先,我们使用 FileInputStream 读取现有的 Excel 文件,并使用 XSSFWorkbook 创建一个工作簿对象。
  • 然后,我们使用 createDrawingPatriarch() 方法创建一个 XSSFDrawing 对象,该对象代表工作表中的绘图层。
  • 接下来,我们使用 createAnchor() 方法创建一个 XSSFClientAnchor 对象,该对象定义了图表在工作表中的位置和大小。
  • 使用 createChart() 方法创建 XSSFChart 对象,表示图表本身。
  • 我们使用 setTitleText() 方法设置图表标题,并使用 setTitleOverlay(false) 方法确保标题不覆盖图表区域。
  • 接下来,我们使用 getOrAddLegend() 方法获取图例对象,并使用 setPosition() 方法设置其位置。
  • 我们使用 createDateAxis() 方法创建 XDDFDateAxis 对象,表示横坐标轴。我们将其设置为日期轴,并设置其格式和标签位置。
  • 然后,我们使用 createValueAxis() 方法创建 XDDFValueAxis 对象,表示纵坐标轴。
  • 使用 XDDFDataSourcesFactory.fromNumericCellRange() 方法创建数据源,指定数据系列的值在工作表中的单元格范围。
  • 使用 createData() 方法创建 XDDFChartData 对象,指定图表类型为折线图,并传递横坐标轴和纵坐标轴对象。
  • 使用 addSeries() 方法将数据系列添加到图表中,并设置每个数据系列的标题、样式和其他属性。
  • 最后,我们使用 plot() 方法绘制图表,并使用 FileOutputStream 将修改后的工作簿保存回 Excel 文件。

4. 总结

本教程介绍了如何使用 Java POI 库在 Excel 中创建折线图。您可以使用此代码示例作为起点,根据您的需要自定义图表。

Java POI 创建 Excel 折线图 - 附详细代码示例

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

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