package com.jiaofb.day09;
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
/**
* @Auther: iteration.0
* @Date: 13/4/2021 - 04 - 13 - 12:59 PM
* @Description: 第一题:
* 使用两种方式读取exam.xls(从附件中下载)中所有的数据。
* @version: 1.0
*/
public class TestExcel {
public static void main(String[] args) {
/**
* 1.创建输入流,读取excel文件
* 2.调用POI API 创建Excel 对象
* 3.获取sheet
* 4.获取所有行
* 5.获取所有单元格
*/
try {
//1.创建输入流,读取excel文件
FileInputStream fis=new FileInputStream("src\\test\\resources\\exam.xls");
//2.调用POI API 创建Excel 对象
Workbook sheets= WorkbookFactory.create(fis);
//关闭流
fis.close();
//3.获取sheet
Sheet sheet= sheets.getSheet("用例");
//4.获取所有行
System.out.println("增强for 循环遍历:");
for (Row row:sheet){
if(row.getRowNum()==0)
continue;
//5.获取所有单元格
for(Cell cell: row){
//把所有单元格cell 都转成String
//枚举:可穷举,作用:防止输入错误的参数
cell.setCellType(CellType.STRING);
System.out.print(cell.getStringCellValue()+" ");
}
System.out.println();
}
System.out.println("普通for 循环遍历:");
int lastRowNum=sheet.getLastRowNum();
for (int i = 1; i <= lastRowNum; i++) {
Row row=sheet.getRow(i);
int lastCellNum=row.getLastCellNum();
for (int j = 0; j <= lastCellNum; j++) {
//Row.MissingCellPolicy.CREATE_NULL_AS_BLANK 防止返回的cell is null
//如果是null new 一个空的cell 返回
//Cell cell=row.getCell(j);
Cell cell=row.getCell(j,Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
cell.setCellType(CellType.STRING);
System.out.print(cell.getStringCellValue()+" ");
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
Ps:
第一步pom.xml 中配置依赖
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.0</version>
</dependency>