使用 Apache POI 库在 Java 中创建 Excel 折线图

本教程将指导您如何使用 Apache POI 库在 Java 中创建 Excel 折线图。我们将学习如何设置日期坐标轴、数据源、图例位置,以及将多个数据系列关联到不同的坐标轴。

代码示例:

package '折线图';

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
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 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);
            XSSFChart chart = drawing.createChart(anchor);
            chart.setTitleText('数据折线图');
            chart.setTitleOverlay(false);

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

            // 设置横坐标轴为日期坐标轴
            XDDFDataSource<?> dateSource = XDDFDataSourcesFactory.fromNumericCellRange(sheet1, new CellRangeAddress(11, 85, 1, 1));
            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++) {
                XSSFRow row = sheet1.getRow(i + 11);
                if (row != null) {
                    Cell cell = row.getCell(1);
                    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, 127, 1, 1));
            XDDFNumericalDataSource<Double> ys1 = XDDFDataSourcesFactory.fromNumericCellRange(sheet1, new CellRangeAddress(1, 127, 0, 0));
            XDDFNumericalDataSource<Double> xs2 = XDDFDataSourcesFactory.fromNumericCellRange(sheet1, new CellRangeAddress(1, 127, 2, 2));
            XDDFNumericalDataSource<Double> ys2 = XDDFDataSourcesFactory.fromNumericCellRange(sheet1, new CellRangeAddress(1, 127, 0, 0));

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

            // 添加第二个数据系列
            XDDFLineChartData.Series series2 = (XDDFLineChartData.Series) data.addSeries(xs2, ys2);
            series2.setTitle('折线图2', null);
            series2.setSmooth(false); // 取消平滑曲线

            // 将第二个数据系列关联到右侧坐标轴
            chart.plot(data);
            chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(1).getIdx().setVal(1);

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

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

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

步骤:

  1. 导入必要库:

    • org.apache.poi.ss.usermodel:用于处理Excel工作簿和工作表
    • org.apache.poi.xddf.usermodel.chart:用于创建图表对象
    • org.apache.poi.xssf.usermodel:用于处理xlsx文件
  2. 读取Excel文件:

    • 使用FileInputStream读取Excel文件
    • 使用XSSFWorkbook创建工作簿对象
    • 使用getSheet()获取工作表对象
  3. 创建图表对象:

    • 使用createDrawingPatriarch()获取绘图对象
    • 使用createAnchor()设置图表位置
    • 使用createChart()创建图表对象
    • 使用setTitleText()设置图表标题
  4. 设置图例位置:

    • 使用getOrAddLegend()获取图例对象
    • 使用setPosition()设置图例位置
  5. 设置横坐标轴:

    • 使用createDateAxis()创建日期坐标轴
    • 使用setCrosses()设置坐标轴交叉位置
    • 使用setTitle()设置坐标轴标题
    • 使用setTickLabelPosition()设置刻度标签位置
  6. 设置时间格式:

    • 使用SimpleDateFormat设置时间格式
    • 遍历数据源,获取每个日期值
    • 使用format()方法格式化日期
  7. 设置纵坐标轴:

    • 使用createValueAxis()创建数值坐标轴
    • 使用setCrosses()设置坐标轴交叉位置
    • 使用setTitle()设置坐标轴标题
  8. 设置数据源:

    • 使用fromNumericCellRange()从Excel单元格范围获取数据源
  9. 添加数据系列:

    • 使用createData()创建图表数据对象
    • 使用addSeries()添加数据系列
    • 使用setTitle()设置数据系列标题
  10. 将数据系列关联到坐标轴:

  • 使用plot()将数据系列关联到坐标轴
  • 使用getIdx()设置数据系列关联到哪个坐标轴
  1. 保存Excel文件:
  • 使用FileOutputStream创建一个输出流
  • 使用write()方法将工作簿写入到输出流
  • 关闭输出流

注意:

  • 将'input-1.xlsx'替换为您的Excel文件路径
  • 将'P1'替换为您的工作表名称
  • 将单元格范围调整为您的数据范围
  • 可以根据需要调整图表选项,例如颜色、字体、样式等

通过以上步骤,您就可以使用Java代码在Excel中创建动态折线图,并根据您的数据进行调整。

祝您编程愉快!

Java POI Excel 折线图创建教程:使用 Apache POI 库生成动态折线图

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

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