使用Apache POI从已有Excel数据创建折线图

本教程将演示如何使用Apache POI库在Java中从现有的Excel文件数据创建折线图。

前提条件

  • 已安装Java开发环境* 已添加Apache POI库到项目中 (可通过Maven或Gradle添加依赖)

代码示例

假设你已经有一个名为'input-1.xlsx'的Excel文件,并且文件中已经包含了'P1'工作表,你可以按照以下步骤读取内容并制作折线图:javaimport 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 org.openxmlformats.schemas.drawingml.x2006.chart.CTBoolean;import org.openxmlformats.schemas.drawingml.x2006.chart.CTChart;import org.openxmlformats.schemas.drawingml.x2006.chart.CTPlotArea;

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 {            // 1. 读取Excel文件            FileInputStream fileIn = new FileInputStream('input-1.xlsx');            XSSFWorkbook workbook = new XSSFWorkbook(fileIn);            XSSFSheet sheet1 = workbook.getSheet('P1');

        // 2. 创建折线图            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);

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

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

        // 5. 设置时间格式            SimpleDateFormat dateFormat = new SimpleDateFormat('yyyy/MM/dd');            for (int i = 0; i < dateSource.getPointCount(); i++) {                XSSFRow 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);                        // 可以根据需要设置日期格式                        bottomAxis.setTickLabelPosition(AxisTickLabelPosition.NEXT_TO);                    }                }            }

        // 6. 设置左侧坐标轴为温度坐标轴            XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT);            leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);            leftAxis.setTitle('温度');

        // 7. 设置右侧坐标轴为数值坐标轴            XDDFValueAxis rightAxis = chart.createValueAxis(AxisPosition.RIGHT);            rightAxis.setCrosses(AxisCrosses.MAX);            rightAxis.setTitle('数据值');

        // 8. 设置数据源            // 假设数据在A2:A128列是日期,B2:B128是温度,C2:C128是数据值            XDDFNumericalDataSource<Double> xs1 = XDDFDataSourcesFactory.fromNumericCellRange(sheet1, new CellRangeAddress(1, 127, 0, 0));            XDDFNumericalDataSource<Double> ys1 = XDDFDataSourcesFactory.fromNumericCellRange(sheet1, new CellRangeAddress(1, 127, 1, 1));            XDDFNumericalDataSource<Double> xs2 = XDDFDataSourcesFactory.fromNumericCellRange(sheet1, new CellRangeAddress(1, 127, 0, 0));            XDDFNumericalDataSource<Double> ys2 = XDDFDataSourcesFactory.fromNumericCellRange(sheet1, new CellRangeAddress(1, 127, 2, 2));

        // 9. 添加数据系列            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); // 取消平滑曲线

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

        // 11. 设置图表样式            XSSFChart xssfChart = (XSSFChart) chart;            CTChart ctChart = xssfChart.getCTChart();            CTPlotArea ctPlotArea = ctChart.getPlotArea();            ctPlotArea.getLineChartArray(0).addNewVaryColors().setVal(true);            ctPlotArea.getLineChartArray(0).addNewVaryColors().setVal(true);            ctChart.getPlotArea().getLineChartArray(0).getSerArray(0).addNewSmooth().setVal(false);            ctChart.getPlotArea().getLineChartArray(0).getSerArray(1).addNewSmooth().setVal(false);            CTBoolean ctBoolean = ctChart.getPlotArea().getLineChartArray(0).addNewVaryColors();            ctBoolean.setVal(true);            ctBoolean = ctChart.getPlotArea().getLineChartArray(0).addNewVaryColors();            ctBoolean.setVal(true);

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

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

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

代码说明:

  1. 读取Excel文件: 代码首先读取名为 'input-1.xlsx' 的Excel文件,并获取名为 'P1' 的工作表。2. 创建折线图: 创建一个 XSSFDrawing 对象用于绘制图表,并使用 XSSFClientAnchor 定义图表在工作表中的位置和大小。然后,使用XDDFChart 对象创建图表,并设置标题。3. 设置图例位置: 使用 XDDFChartLegend 对象设置图例位置为底部。4. 设置横坐标轴: 使用 XDDFDateAxis 将横坐标轴设置为日期坐标轴,并设置轴标题、刻度线位置等属性。5. 设置时间格式: 使用 SimpleDateFormat 设置日期格式。6. 设置左侧坐标轴: 使用 XDDFValueAxis 设置左侧坐标轴为数值轴,并设置轴标题等属性。7. 设置右侧坐标轴: 类似于步骤6,设置右侧坐标轴为数值轴。8. 设置数据源: 使用 XDDFDataSourcesFactory 从工作表中读取数据,并创建 XDDFNumericalDataSource 对象作为数据源。9. 添加数据系列: 使用 XDDFLineChartData 添加两个数据系列,分别对应左侧和右侧坐标轴,并设置数据系列的标题和样式。10. 关联数据系列到坐标轴: 将第二个数据系列关联到右侧坐标轴。11. 设置图表样式: 可以根据需要设置图表样式,例如颜色、线条样式等。12. 保存Excel文件: 最后,将修改后的Excel文件保存到磁盘。

通过以上步骤,您可以使用Apache POI库轻松地从现有的Excel数据创建折线图,并根据需要进行自定义设置。

使用Apache POI创建Excel折线图 - 从已有数据生成图表

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

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