Apache POI读取Excel

时间:2021-08-04 20:51:08

1、pom.xml配置文件

 <!-- 配置Apache POI -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.0</version>
</dependency>

2、读取Excel的Java代码

 @Test
public void readExcelTest() throws IOException {
File xlsFile = new File("E:\\book.xlsx");
// 获得工作簿
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(xlsFile));
// 获得sheet
XSSFSheet sheet = wb.getSheetAt(0);
int rows = sheet.getPhysicalNumberOfRows();
String split = "**********";
for (int i = 0; i < rows; i++) {
// 获取第i行
XSSFRow row = sheet.getRow(i);
// 列数
short nums = row.getLastCellNum();
for (int j = 0; j < nums; j++) {
Cell cell = row.getCell(j);
System.out.print(cell + split);
}
System.out.println();
}
}

3、Excel文件和测试结果

Apache POI读取Excel

Apache POI读取Excel

以上只是java读取Excel应用演示,代码中没有对对象的非空判定,需要的童鞋可自行加上判定,使代码更健壮。