要使用 Java 调用 Excel 的功能,你可以使用 Apache POI 库。下面是一个示例代码,演示如何使用 Java 创建一个 Excel 文件并在其中绘制折线图。

首先,你需要在项目中添加 Apache POI 的依赖。你可以在 Maven 项目中的 pom.xml 文件中添加以下依赖:

<dependencies>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>4.1.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>4.1.2</version>
    </dependency>
</dependencies>

接下来,你可以使用以下代码创建一个 Excel 文件,并在其中绘制折线图:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

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

public class ExcelChartExample {
    public static void main(String[] args) {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("Data");

            // 创建数据
            Row row1 = sheet.createRow(0);
            row1.createCell(0).setCellValue("X");
            row1.createCell(1).setCellValue("Y");

            for (int i = 1; i <= 10; i++) {
                Row row = sheet.createRow(i);
                row.createCell(0).setCellValue(i);
                row.createCell(1).setCellValue(Math.sin(i));
            }

            // 创建折线图
            Drawing<?> drawing = sheet.createDrawingPatriarch();
            ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 5, 1, 15, 15);
            Chart chart = drawing.createChart(anchor);
            ChartLegend legend = chart.getOrCreateLegend();
            legend.setPosition(LegendPosition.RIGHT);

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

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

            DataSources xs = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 10, 0, 0));
            DataSources ys = DataSources.fromNumericCellRange(sheet, new CellRangeAddress(1, 10, 1, 1));

            LineChartSeries series = data.addSeries(xs, ys);
            series.setTitle(sheet.getRow(0).getCell(1).getStringCellValue());

            chart.plot(data, xAxis, yAxis);

            // 保存 Excel 文件
            try (FileOutputStream fileOut = new FileOutputStream("output.xlsx")) {
                workbook.write(fileOut);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

此代码将创建一个名为'Data' 的工作表,并在其中添加一列 X 值和一列 Y 值。然后,它将创建一个折线图,并将数据绘制在图表上。最后,它将保存 Excel 文件为 'output.xlsx'。

请注意,此代码使用 POI 的 XSSFWorkbook 类来处理 .xlsx 文件格式。如果你要处理 .xls 文件格式,请改用 HSSFWorkbook 类。

Java 生成 Excel 折线图:使用 Apache POI 绘制数据

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

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