一、easyexcel
引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.3.2</version>
</dependency>
//开始读取(每一条数据都存在exceelDto中),1、.read读取excel文件,指定文件路径。2、head指定映射的实体类。3、sheet读取哪个表格。4、doReadSync执行同步读取操作,所有数据都被读取并处理完成后再返回
List<ExcelDto> list = EasyExcel.read("src/main/resources/data33.xlsx").head(ExcelDto.class).sheet("Sheet1").doReadSync();
//遍历
for (ExcelDto excelDto : list) {
System.out.println(excelDto.getParams());
System.out.println(excelDto.getValse());
}
//写入,先添加数据
ExcelDto excelDto = new ExcelDto("test4","value4");
ExcelDto excelDto2 = new ExcelDto("test5","value5");
ExcelDto excelDto3 = new ExcelDto("test6","value6");
List<ExcelDto> allDatas = new ArrayList<ExcelDto>();
allDatas.add(excelDto2);
allDatas.add(excelDto3);
allDatas.add(excelDto);
//写入文件的路径和实体类表格,执行写入操作指定写入的数据
EasyExcel.write("src/main/resources/data35.xlsx", ExcelDto.class).sheet(0).doWrite(allDatas);
二、hutool解析
引入依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.4.7</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.16</version>
</dependency>
1、读取所有
public void test1(){
File file = new File("src/main/resources/data.xlsx");
ExcelReader excelReader = ExcelUtil.getReader(file,0);
List<Map<String, Object>> list1 = excelReader.readAll();
ExcelDataDTO excelDataDTO = new ExcelDataDTO();
//把读取到的数据,封装到实体类中
for (Map<String, Object> stringObjectMap : list1) {
Set<String> set = stringObjectMap.keySet();
for (String s : set) {
Object value = stringObjectMap.get(s);
System.out.println("key:"+s+",value值"+value);
if (s.equalsIgnoreCase("序号")){
excelDataDTO.setNo((Long) value);
}else if (s.equalsIgnoreCase("描述")){
excelDataDTO.setDesc((String) value);
}else if (s.equalsIgnoreCase("接口地址")){
excelDataDTO.setUrl((String) value);
}else if (s.equalsIgnoreCase("传参")){
excelDataDTO.setParams((String) value);
}else {
System.out.println("未匹配到");
}
}
String url = excelDataDTO.getUrl();
System.out.println("url地址为"+url);
}
}
也可以调用方法直接封装进去
File file = new File("src/main/resources/data.xlsx");
ExcelReader excelReader = ExcelUtil.getReader(file, 0);
List<ExcelDataDTO> lists = excelReader.readAll(ExcelDataDTO.class);
2、读取指定数据
@Test(dataProvider = "datas")
public void test2(ExcelDataDTO excelDataDTO){
excelDataDTO.getUrl();
System.out.println(excelDataDTO.getUrl());
}
@DataProvider
public static Object[] datas() {
File file = new File("src/main/resources/data33.xlsx");
//读取指定列
ExcelReader excelReader = ExcelUtil.getReader(file, 0);
//读取到指定行,并封装到实体对象中
List<ExcelDataDTO> lists = excelReader.read(0, 1, 1, ExcelDataDTO.class);
lists.toArray();
return lists.toArray();
}
三、原始的poi