Java

java怎么读取本地excel

小亿
107
2024-08-01 18:59:12
栏目: 编程语言

Java可以通过使用Apache POI库来读取本地Excel文件。以下是一个简单的示例代码:

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

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

public class ExcelReader {

    public static void main(String[] args) {
        try {
            FileInputStream file = new FileInputStream("example.xlsx");

            Workbook workbook = WorkbookFactory.create(file);
            Sheet sheet = workbook.getSheetAt(0);

            for (Row row : sheet) {
                for (Cell cell : row) {
                    switch (cell.getCellType()) {
                        case STRING:
                            System.out.print(cell.getStringCellValue() + "\t");
                            break;
                        case NUMERIC:
                            System.out.print(cell.getNumericCellValue() + "\t");
                            break;
                        case BOOLEAN:
                            System.out.print(cell.getBooleanCellValue() + "\t");
                            break;
                        default:
                            System.out.print("\t");
                    }
                }
                System.out.println();
            }

            file.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在这个示例中,我们首先创建一个FileInputStream对象,指定要读取的Excel文件的路径。然后使用WorkbookFactory类的create方法创建一个Workbook对象,再从中获取第一个Sheet。接着我们遍历Sheet中的每一行和每一个单元格,并根据单元格的类型来读取相应的值。最后,关闭文件流。

请注意,你需要包含Apache POI库的相关依赖,例如在Maven项目中添加以下依赖:

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

这样就可以使用Java读取本地Excel文件了。

0
看了该问题的人还看了