要在 Java 中导入 Excel 文件,可以使用 Apache POI 库。下面是一个简单的示例代码,展示了如何使用 POI 库从 Excel 文件中读取数据:

import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.*;

public class ExcelImportExample {
    public static void main(String[] args) {
        try {
            FileInputStream file = new FileInputStream('path/to/excel/file.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();
            }
            
            workbook.close();
            file.close();
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在上面的代码中,首先使用 FileInputStream 类来读取 Excel 文件。然后,使用 WorkbookFactory 类的 create 方法创建 Workbook 对象,接着使用 getSheetAt 方法获取第一个工作表。然后,使用嵌套的循环遍历所有的行和列,根据单元格的类型使用不同的方法来获取单元格的值。

请注意,上面的代码假设 Excel 文件的第一个工作表是要读取的工作表。如果要读取其他工作表,可以使用 getSheet 方法,并传递工作表的名称或索引作为参数。

另外,你需要将代码中的 'path/to/excel/file.xlsx' 替换为实际的 Excel 文件路径。

Java Excel 导入教程:使用 Apache POI 库读取数据

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

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