java如何读取excel文件
使用 Apache POI 读取 Excel 文件
Apache POI 是 Java 中处理 Office 文档的流行库,支持 .xls(HSSF)和 .xlsx(XSSF)格式。
添加 Maven 依赖:
<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>
读取 .xlsx 文件示例:
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
public class ExcelReader {
public static void main(String[] args) throws Exception {
String filePath = "example.xlsx";
FileInputStream fis = new FileInputStream(filePath);
Workbook workbook = WorkbookFactory.create(fis);
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
String cellValue = "";
switch (cell.getCellType()) {
case STRING:
cellValue = cell.getStringCellValue();
break;
case NUMERIC:
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case BOOLEAN:
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
default:
cellValue = "";
}
System.out.print(cellValue + "\t");
}
System.out.println();
}
workbook.close();
fis.close();
}
}
使用 EasyExcel 读取大文件
EasyExcel 是阿里开源的库,适合处理大数据量的 Excel 文件,内存占用更低。
添加 Maven 依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.3.2</version>
</dependency>
定义实体类:
@Data
public class DemoData {
@ExcelProperty("列名1")
private String column1;
@ExcelProperty("列名2")
private Integer column2;
}
监听器方式读取:
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
public class DemoDataListener implements ReadListener<DemoData> {
@Override
public void invoke(DemoData data, AnalysisContext context) {
System.out.println(data);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
System.out.println("读取完成");
}
}
调用读取方法:
EasyExcel.read("large_file.xlsx", DemoData.class, new DemoDataListener())
.sheet()
.doRead();
处理日期和特殊格式
对于日期类型单元格,需要特殊处理:
if (cell.getCellType() == CellType.NUMERIC && DateUtil.isCellDateFormatted(cell)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
cellValue = sdf.format(cell.getDateCellValue());
}
性能优化建议
大数据量文件建议使用流式读取模式,避免内存溢出。Apache POI 提供 SXSSFWorkbook 用于写操作,读操作可使用 XSSFReader 进行 SAX 解析。
EasyExcel 默认采用流式解析,适合处理 GB 级别的 Excel 文件,推荐在数据量超过 10 万行时使用。







