本教程将介绍使用 Java POI 库创建 Excel 折线图,并涵盖一些常见的功能,例如设置日期坐标轴、添加多个数据系列、自定义图例和坐标轴等。

代码示例

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 org.openxmlformats.schemas.drawingml.x2006.chart.CTBoolean;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ExcelChartExample04 {

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

            // 创建折线图
            XSSFDrawing drawing = sheet1.createDrawingPatriarch();
            XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 129, 10, 149);
            XDDFChart chart = drawing.createChart(anchor);
            chart.setTitleText('数据折线图');
            chart.setTitleOverlay(false);

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

            // 设置横坐标轴为日期坐标轴
            XDDFDataSource<?> dateSource = XDDFDataSourcesFactory.fromArray(new String[] {'A2:A127'});
            XDDFDateAxis bottomAxis = chart.createDateAxis(AxisPosition.BOTTOM);
            bottomAxis.setCrosses(AxisCrosses.AUTO_ZERO);
            bottomAxis.setTitle('时间');
            bottomAxis.setTickLabelPosition(AxisTickLabelPosition.NEXT_TO);

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

            // 设置左侧坐标轴为温度坐标轴
            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, 127, 2, 2));
            XDDFNumericalDataSource<Double> ys1 = XDDFDataSourcesFactory.fromNumericCellRange(sheet1, new CellRangeAddress(1, 127, 0, 0));
            XDDFNumericalDataSource<Double> ys2 = XDDFDataSourcesFactory.fromNumericCellRange(sheet1, new CellRangeAddress(1, 127, 1, 1));

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

            // 添加第二个数据系列
            XDDFLineChartData.Series series2 = (XDDFLineChartData.Series) data.addSeries(xs1, ys2);
            series2.setTitle('折线图2', null);
            series2.setSmooth(false);
            chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(1).getOrder().setVal(1);

            // 设置次要垂直坐标轴
            CTLineSer ctLineSer = chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(1);
            if (ctLineSer.getDLbls() == null) {
                ctLineSer.addNewDLbls();
            }
            ctLineSer.getDLbls().setShowLegendKey(ctBoolean);
            ctLineSer.getDLbls().setShowVal(ctBoolean);
            ctLineSer.getDLbls().setShowCatName(ctBoolean);
            ctLineSer.getDLbls().setShowSerName(ctBoolean);

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

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

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

代码解释

  1. 读取 Excel 文件: 使用 FileInputStream 读取 Excel 文件,并使用 XSSFWorkbook 创建工作簿对象。
  2. 获取工作表: 使用 getSheet() 获取名为 'P1' 的工作表对象。
  3. 创建折线图: 使用 createDrawingPatriarch() 创建绘图对象,并使用 createAnchor() 设置折线图的位置。
  4. 设置标题: 使用 setTitleText() 设置折线图标题。
  5. 设置图例: 使用 getOrAddLegend() 获取或添加图例对象,并使用 setPosition() 设置图例位置。
  6. 设置日期坐标轴: 使用 createDateAxis() 创建日期坐标轴,并使用 setTitle() 设置坐标轴标题。
  7. 设置时间格式: 使用 SimpleDateFormat 设置日期格式,并将 Excel 文件中的日期数据转换为字符串格式。
  8. 设置数值坐标轴: 使用 createValueAxis() 创建数值坐标轴,并使用 setTitle() 设置坐标轴标题。
  9. 设置数据源: 使用 fromNumericCellRange() 从 Excel 文件中读取数据,并创建 XDDFNumericalDataSource 对象。
  10. 添加数据系列: 使用 createData() 创建数据系列,并使用 addSeries() 添加多个数据系列。
  11. 设置次要垂直坐标轴: 设置次要垂直坐标轴的显示选项,包括是否显示图例键、数据值、类别名称和系列名称。
  12. 保存 Excel 文件: 使用 FileOutputStream 保存修改后的 Excel 文件。

总结

本教程介绍了使用 Java POI 创建 Excel 折线图的基本步骤,并演示了如何设置日期坐标轴、添加多个数据系列、自定义图例和坐标轴等功能。通过学习本教程,您可以根据自己的需求创建各种类型的 Excel 图表。

Java POI Excel 折线图创建教程:带日期坐标轴和多个数据系列

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

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