温馨提示×

java怎么获取excel数据

小亿
97
2023-11-07 21:07:51
栏目: 编程语言

要在Java中获取Excel数据,可以使用Apache POI库。以下是获取Excel数据的基本步骤:

  1. 导入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>
  1. 创建一个Workbook对象,打开Excel文件:
File file = new File("path/to/excel.xlsx"); // 替换为实际的Excel文件路径
Workbook workbook = WorkbookFactory.create(file);
  1. 获取要读取的工作表:
Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
  1. 遍历工作表中的每一行和每一列,并获取单元格的值:
for (Row row : sheet) {
    for (Cell cell : row) {
        String cellValue = cell.getStringCellValue();
        System.out.print(cellValue + "\t");
    }
    System.out.println(); // 换行
}

完整代码示例:

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

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

public class ExcelReader {
    public static void main(String[] args) {
        try {
            File file = new File("path/to/excel.xlsx"); // 替换为实际的Excel文件路径
            FileInputStream fis = new FileInputStream(file);
            Workbook workbook = new XSSFWorkbook(fis);

            Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表

            for (Row row : sheet) {
                for (Cell cell : row) {
                    String cellValue = cell.getStringCellValue();
                    System.out.print(cellValue + "\t");
                }
                System.out.println(); // 换行
            }

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

注意:上述代码假设Excel文件的扩展名为.xlsx。如果Excel文件的扩展名为.xls,需要使用HSSFWorkbook代替XSSFWorkbook

0