导入时的坑:
如果excel导入的数据类型 和 bean的数据类型不匹配,会报错
导入依赖
<!--excel 基于poi的再次封装-->
<dependency>
<groupId>com.jvm123</groupId>
<artifactId>excel-converter</artifactId>
<version>1.0</version>
</dependency>
Excel-converter 是一个基于poi的,将excel中的数据读取为java对象,以及将java对象的list导出到excel的工具 。
/**
* @Description
* @Author by mocar小师兄
* @Date 2020/5/12 22:45
**/
@Component
public class ExcelHandleUtils {
//解析为map
public Result uploadFileToMap(MultipartFile file) throws IOException {
try {
String fileName = file.getOriginalFilename();
String fileExtName = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
//获取输入流
InputStream is = file.getInputStream();
ExcelImporter excelImporter = new ExcelImporter();
excelImporter.setExcelProperties(getExcelHandleProperties());
// 读取为 List<Map> 其中,map结果:key为bean的变量名
List<Map<String, Object>> excelMapList = excelImporter.convertToMap(is);
for (Map<String, Object> map : excelMapList) {
System.out.println(map);
}
} catch (IOException e) {
e.printStackTrace();
}
return ResultUtil.error("Excel解析失败");
}
//封装为obj
public <T> Result uploadFileToObj(MultipartFile file,Class<T> tClazz) throws IOException {
try {
String fileName = file.getOriginalFilename();
String fileExtName = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
//获取输入流
InputStream is = file.getInputStream();
ExcelImporter excelImporter = new ExcelImporter();
excelImporter.setExcelProperties(getExcelHandleProperties());
// 读取为 List<对象>
//坑:如果excel导入的数据类型 和 bean的数据类型不匹配,会报错
//List<T> convertList = excelImporter.convert(file.getInputStream(), tClazz);
Date date = new Date();
System.out.println(date);
List<T> convertList = excelImporter.convert(file.getInputStream(), tClazz);
for (T t : convertList) {
User user = (User) t;
System.out.println(user);
}
} catch (IOException e) {
e.printStackTrace();
}
return ResultUtil.error("Excel解析失败");
}
private ExcelProperties getExcelHandleProperties(){
ExcelProperties properties = new ExcelProperties();
//要导入的表格(sheet)在excel文件中的索引顺序
properties.setSheetIndex(0);
//对应每一列的说明的行的序号(可无)--> 即别名
properties.setCommentRowIndex(0);
//对应java中bean属性名称的行的序号 --> 即变量名
properties.setNameRowIndex(1);
//要获取的数据开始行的序号-->即数据从第几行开始
properties.setFirstDataRowIndex(2);
//要获取的数据结束行的序号(可无)-->即最后一行数据在第几行
//properties.setLastDataRowIndex(3);
//要获取的数据的条数(可无)
//properties.setDataRowNum(2);
return properties;
}
}
参考:
http://jvm123.com/2019/08/excel-converter.html