使用 Java 代码读取 Excel 文件并生成折线图,你可以使用 Apache POI 库来处理 Excel 文件,以及使用 JFreeChart 库来制作折线图。

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

<dependencies>
    <!-- Apache POI -->
    <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>
    
    <!-- JFreeChart -->
    <dependency>
        <groupId>org.jfree</groupId>
        <artifactId>jfreechart</artifactId>
        <version>1.5.3</version>
    </dependency>
</dependencies>

接下来,你可以使用以下 Java 代码来读取 Excel 文件中的内容并制作折线图:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.data.category.DefaultCategoryDataset;

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

public class ExcelLineChart {
    public static void main(String[] args) {
        String filePath = "input-1.xlsx";
        String sheetName = "P1";
        
        try (Workbook workbook = new XSSFWorkbook(new File(filePath))) {
            Sheet sheet = workbook.getSheet(sheetName);
            
            // 读取数据
            DefaultCategoryDataset dataset = new DefaultCategoryDataset();
            for (Row row : sheet) {
                Cell xCell = row.getCell(0);
                Cell yCell = row.getCell(1);
                if (xCell != null && yCell != null) {
                    String xValue = xCell.getStringCellValue();
                    double yValue = yCell.getNumericCellValue();
                    dataset.addValue(yValue, "Series", xValue);
                }
            }
            
            // 创建折线图
            JFreeChart chart = ChartFactory.createLineChart(
                    "Line Chart", // 图表标题
                    "X", // X轴标签
                    "Y", // Y轴标签
                    dataset // 数据集
            );
            
            // 保存图表为图片文件
            File outputFile = new File("output.png");
            ChartUtilities.saveChartAsPNG(outputFile, chart, 800, 600);
            
            System.out.println("折线图已生成:" + outputFile.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

请确保将代码中的input-1.xlsx替换为你实际的 Excel 文件路径。运行代码后,将生成一个名为output.png的折线图文件。

这只是一个简单的示例,你可以根据你的实际需求进行修改和扩展。

Java 读取 Excel 文件并生成折线图

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

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