欢迎访问宙启技术站
智能推送

如何在Java中读写Excel文件

发布时间:2023-07-29 19:25:00

在Java中,可以使用多种方式来读写Excel文件,包括使用开源库Apache POI和JExcel等。下面将详细介绍使用Apache POI的方法。

Apache POI是一个流行的Java开发库,用于处理Microsoft Office格式文档,包括Excel文件。它提供了读写Excel文件的API,可以操作不同版本的Excel文件。

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

<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>

完成依赖项的添加后,你可以使用以下代码来读取Excel文件中的数据:

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

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

public class ExcelReader {

    public static void main(String[] args) {
        try {
            FileInputStream file = new FileInputStream("path/to/your/excel/file.xlsx");

            Workbook workbook = new XSSFWorkbook(file);

            Sheet sheet = workbook.getSheetAt(0);

            for (Row row : sheet) {
                for (Cell cell : row) {
                    CellType cellType = cell.getCellType();
                    if (cellType == CellType.STRING) {
                        System.out.print(cell.getStringCellValue() + "\t");
                    } else if (cellType == CellType.NUMERIC) {
                        System.out.print(cell.getNumericCellValue() + "\t");
                    }
                }
                System.out.println();
            }

            workbook.close();
            file.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

以上代码将读取Excel文件的 个工作表,并将每个单元格的值打印输出。

如果你需要在Excel文件中写入数据,可以使用以下代码:

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

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

public class ExcelWriter {

    public static void main(String[] args) {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");
        
        Row row = sheet.createRow(0);
        
        Cell cell = row.createCell(0);
        cell.setCellValue("Hello");
        
        try {
            FileOutputStream file = new FileOutputStream("path/to/your/excel/file.xlsx");
            workbook.write(file);
            
            workbook.close();
            file.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

以上代码将创建一个新的Excel文件,并在 个工作表的 个单元格中写入"Hello"。

通过使用Apache POI库,你可以方便地读写Excel文件,操作单元格的内容和样式,插入图表和公式等。希望这些例子能帮助你开始在Java中读写Excel文件。