java如何导入excel
导入Excel文件的方法
在Java中导入Excel文件通常使用Apache POI或JExcelAPI等库。以下是使用Apache POI的详细方法。
使用Apache POI导入Excel
确保项目中已添加Apache POI依赖。Maven项目可在pom.xml中添加以下依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
读取Excel文件内容
创建一个方法读取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 readExcel(String filePath) {
try (FileInputStream fis = new FileInputStream(filePath);
Workbook workbook = new XSSFWorkbook(fis)) {
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("UNKNOWN\t");
}
}
System.out.println();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
处理不同Excel版本
对于.xls格式的旧版Excel文件,使用HSSFWorkbook:
Workbook workbook = new HSSFWorkbook(fis);
对于.xlsx格式的新版Excel文件,使用XSSFWorkbook:

Workbook workbook = new XSSFWorkbook(fis);
高级操作示例
读取特定单元格数据:
Sheet sheet = workbook.getSheet("Sheet1");
Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
String value = cell.getStringCellValue();
System.out.println("Cell A1 value: " + value);
注意事项
- 文件路径需正确,否则会抛出
FileNotFoundException。 - 处理完数据后需关闭资源,推荐使用
try-with-resources语句。 - 大型Excel文件可能占用较多内存,可考虑使用
SXSSFWorkbook进行流式处理。
替代方案
若需更简洁的API,可考虑使用EasyExcel库:
// EasyExcel示例代码
EasyExcel.read(filePath, DemoData.class, new DemoDataListener()).sheet().doRead();
以上方法覆盖了Java导入Excel的基本和高级操作,根据实际需求选择合适的实现方式。






