Java Apache POI 生成Excel折线图教程

本教程将演示如何使用Apache POI库在Excel文件中创建折线图。我们将涵盖以下内容:

  1. 读取Excel文件中的数据2. 使用Apache POI创建折线图3. 设置图表标题、图例和轴标签4. 将图表保存到Excel文件

代码示例javaimport org.apache.poi.ss.usermodel.;import org.apache.poi.xssf.usermodel.;import org.apache.poi.xssf.usermodel.charts.*;

import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;

public class ExcelChartExample01 {

public static void main(String[] args) {        try {            // 读取Excel文件            FileInputStream fileIn = new FileInputStream('巴新EDEVU水库数据处理表.xls');            Workbook workbook = new XSSFWorkbook(fileIn);            Sheet sheet = workbook.getSheet('P9');

        // 创建折线图            XSSFDrawing drawing = (XSSFDrawing) sheet.createDrawingPatriarch();            XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 4, 1, 10, 20);            XSSFChart chart = drawing.createChart(anchor);            XDDFChartLegend legend = chart.getOrAddLegend();            legend.setPosition(LegendPosition.BOTTOM);

        // 创建数据系列            XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);            XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT);            leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);

        // 创建数据源            ChartDataSource<Number> xs = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(11, 85, 0, 0));            ChartDataSource<Number> ys = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(11, 85, 2, 2));

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

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

        // 保存Excel文件            FileOutputStream fileOut = new FileOutputStream('巴新EDEVU水库数据处理表.xls');            workbook.write(fileOut);            fileOut.close();

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

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

解决 '程序包org.apache.poi.xssf.usermodel.charts不存在' 错误

这个错误是由于缺少Apache POI的依赖库导致的。请确保在项目中添加了正确的Apache POI依赖库。

**Maven:**xml org.apache.poi poi 4.1.2 org.apache.poi poi-ooxml 4.1.2

非Maven项目:

手动下载所需的Apache POI JAR文件,并将其添加到项目的类路径中。

希望本教程能帮助你在Java应用程序中使用Apache POI创建Excel折线图!

Java Apache POI 生成Excel折线图教程

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

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