java如何导入excel
使用Apache POI库导入Excel
Apache POI是Java处理Microsoft Office文档的流行库,支持Excel的读写。
添加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>
读取Excel文件示例代码:
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
public class ExcelReader {
public static void readExcel(String filePath) {
try (FileInputStream fis = new FileInputStream(filePath);
Workbook workbook = WorkbookFactory.create(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("\t");
}
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用EasyExcel库导入Excel
EasyExcel是阿里开源的Excel处理工具,内存占用低且API简单。
添加Maven依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.3.2</version>
</dependency>
定义数据模型类:
@Data
public class DemoData {
@ExcelProperty("姓名")
private String name;
@ExcelProperty("年龄")
private Integer age;
}
读取Excel文件示例代码:
import com.alibaba.excel.EasyExcel;
import java.util.List;
public class ExcelReader {
public static void readExcel(String filePath) {
List<DemoData> list = EasyExcel.read(filePath)
.head(DemoData.class)
.sheet()
.doReadSync();
list.forEach(System.out::println);
}
}
使用JExcelAPI导入Excel
JExcelAPI是另一个轻量级的Java Excel处理库。
添加Maven依赖:
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
读取Excel文件示例代码:
import jxl.*;
import java.io.File;
public class ExcelReader {
public static void readExcel(String filePath) {
try {
Workbook workbook = Workbook.getWorkbook(new File(filePath));
Sheet sheet = workbook.getSheet(0);
for (int i = 0; i < sheet.getRows(); i++) {
for (int j = 0; j < sheet.getColumns(); j++) {
Cell cell = sheet.getCell(j, i);
System.out.print(cell.getContents() + "\t");
}
System.out.println();
}
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
性能与适用场景比较
Apache POI功能最全面,支持.xls和.xlsx格式,适合复杂场景。
EasyExcel内存占用低,适合大数据量处理,API简洁。
JExcelAPI只支持.xls格式,轻量级但功能有限。
根据项目需求选择合适的库,大数据量推荐EasyExcel,复杂操作推荐Apache POI。







