使用 Java 调用 Excel 功能并在 Excel 文件中绘制折线图,可以使用 Apache POI 库来实现。下面是一个简单的示例代码,演示了如何使用 Java 调用 Excel 的功能来绘制折线图。

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xddf.usermodel.chart.*;
import org.apache.poi.xssf.usermodel.*;

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

public class ExcelLineChartExample {
    public static void main(String[] args) {
        // 创建 Excel 工作簿
        try (Workbook workbook = new XSSFWorkbook()) {
            // 创建 Excel 工作表
            Sheet sheet = workbook.createSheet('折线图示例');

            // 创建数据行
            Row row1 = sheet.createRow(0);
            row1.createCell(0).setCellValue('月份');
            row1.createCell(1).setCellValue('销售额');

            Row row2 = sheet.createRow(1);
            row2.createCell(0).setCellValue('1月');
            row2.createCell(1).setCellValue(100);

            Row row3 = sheet.createRow(2);
            row3.createCell(0).setCellValue('2月');
            row3.createCell(1).setCellValue(200);

            Row row4 = sheet.createRow(3);
            row4.createCell(0).setCellValue('3月');
            row4.createCell(1).setCellValue(150);

            // 创建折线图
            Drawing<?> drawing = sheet.createDrawingPatriarch();
            ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 4, 0, 10, 15);

            Chart chart = drawing.createChart(anchor);
            ChartLegend legend = chart.getOrCreateLegend();
            legend.setPosition(LegendPosition.TOP_RIGHT);

            LineChartData data = chart.getChartDataFactory().createLineChartData();

            // 设置 X 轴数据
            ChartAxis xAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM);
            ValueAxis yAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT);
            xAxis.setCrosses(AxisCrosses.AUTO_ZERO);

            // 设置 Y 轴数据
            ChartDataSource<Number> xs = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 3, 0, 0));
            ChartDataSource<Number> ys = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 3, 1, 1));

            // 添加折线图数据
            data.addSeries(xs, ys);

            // 绘制折线图
            chart.plot(data, xAxis, yAxis);

            // 保存 Excel 文件
            try (FileOutputStream fileOut = new FileOutputStream('折线图示例.xlsx')) {
                workbook.write(fileOut);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这段代码创建了一个 Excel 工作簿,并在工作表中创建了一些数据。然后,使用 Apache POI 的绘图功能创建了一个折线图,并将数据添加到折线图中。最后,将 Excel 文件保存到磁盘上。

请确保你已经在项目中添加了 Apache POI 的依赖,以便编译和运行上述代码。

Java 使用 Apache POI 生成 Excel 折线图

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

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