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);

            // 将 series3 的 y 轴设置为 rightAxis
            series3.setYAxis(rightAxis);

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

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

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

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

代码解析:

  1. 导入必要的类: 代码首先导入了 Apache POI 库中用于操作 Excel 文件和创建图表的相关类。
  2. 读取 Excel 文件: 使用 FileInputStream 读取名为 'input.xlsx' 的 Excel 文件,并使用 XSSFWorkbook 创建工作簿对象。
  3. 创建折线图:
    • 获取工作表: 使用 workbook.getSheet('P1') 获取名为 'P1' 的工作表。
    • 创建绘图区: 使用 sheet1.createDrawingPatriarch() 创建绘图区对象。
    • 创建图表锚点: 使用 drawing.createAnchor() 创建图表锚点,用于指定图表在工作表中的位置和大小。
    • 创建图表: 使用 drawing.createChart(anchor) 创建图表对象,并指定图表类型为折线图。
    • 设置图表标题: 使用 chart.setTitleText('数据折线图') 设置图表标题,并使用 chart.setTitleOverlay(false) 将标题放置在图表上方。
  4. 设置图例:
    • 获取图例对象: 使用 chart.getOrAddLegend() 获取图例对象。
    • 设置图例位置: 使用 legend.setPosition(LegendPosition.BOTTOM) 将图例放置在图表下方。
  5. 设置坐标轴:
    • 创建横坐标轴: 使用 chart.createDateAxis(AxisPosition.BOTTOM) 创建横坐标轴,并将其设置为日期坐标轴。
    • 设置横坐标轴格式: 使用 SimpleDateFormat 设置日期格式,并使用 bottomAxis.setTickLabelPosition(AxisTickLabelPosition.NEXT_TO) 将刻度标签放置在刻度线旁边。
    • 创建纵坐标轴: 使用 chart.createValueAxis(AxisPosition.LEFT) 创建纵坐标轴,并设置其格式。
    • 创建次要纵坐标轴: 使用 chart.createValueAxis(AxisPosition.RIGHT) 创建次要纵坐标轴,并设置其格式。
  6. 设置数据源:
    • 使用 XDDFDataSourcesFactory.fromNumericCellRange() 从工作表中读取数据,创建数据源对象。
  7. 添加数据系列:
    • 创建数据系列: 使用 chart.createData(ChartTypes.LINE, bottomAxis, leftAxis) 创建数据系列,并指定图表类型为折线图,横坐标轴和纵坐标轴。
    • 添加数据系列: 使用 data.addSeries(xs, ys) 将数据源添加到数据系列中。
    • 设置数据系列格式: 设置数据系列的标题、平滑度、标记样式等。
  8. 添加次要数据系列:
    • 创建次要数据系列: 与添加主数据系列类似,创建次要数据系列并设置其格式。
    • 将次要数据系列关联到次要纵坐标轴: 使用 series3.setYAxis(rightAxis) 将次要数据系列的 y 轴设置为次要纵坐标轴。
  9. 绘制图表:
    • 使用 chart.plot(data) 绘制图表。
  10. 保存 Excel 文件:
    • 使用 FileOutputStream 创建输出流,将修改后的工作簿保存到名为 'output.xlsx' 的文件中。

错误解决:

您遇到的 java: 找不到符号 错误是由于使用的 Apache POI 版本过旧导致的。CTLineSer 接口的 addNewAxId() 方法在较新版本的 POI 中才被引入。

要解决此错误,请尝试以下步骤:

  1. 升级 Apache POI 版本: 将您的项目中使用的 Apache POI 库升级到最新版本。您可以从 Apache POI 官网下载最新版本的 jar 包。
  2. 更新依赖项: 如果您使用 Maven 或 Gradle 等构建工具管理依赖项,请更新您的项目配置文件,使用最新版本的 Apache POI 依赖项。
  3. 重新编译运行: 更新 Apache POI 版本后,重新编译并运行您的代码。

通过升级 Apache POI 版本,您将能够使用 series3.setYAxis(rightAxis) 方法将次要数据系列关联到次要纵坐标轴,从而解决错误并成功创建包含两个纵坐标轴的折线图。

使用Apache POI创建Excel折线图详解(Java)

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

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