踩了很多坑就不说了,上干货
首先引入这两个依赖:
只需要这两个依赖就可以解析xls和xlsx文件
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.0.5</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.16</version>
</dependency>
接收前端传过来的文件,前端怎么传可以看我另一篇博文:angularJS上传文件.
解析excel:
这边是这样的,alias这个map的键为上传的表格的标题行,值为自定义实体类的属性名,将标题行与属性一一对应,最后excelReader.readAll(ExcelOrderDTO.class)将表格每一行数据封装进结果集合中
ps:ExcelOrderDTO是用来存放表格内容的实体类
@ResponseBody
@PostMapping("/attachmentUpload")
public String parseExcel(MultipartFile file){
try {
InputStream fileInputStream = file.getInputStream();
ExcelReader excelReader = ExcelUtil.getReader(fileInputStream);
//自定义标题别名
Map<String, String> alias = Maps.newLinkedHashMap();
alias.put(ExcelConstants.NUM, "num");
alias.put(ExcelConstants.PROPOSERNAME, "proposerName");
alias.put(ExcelConstants.HOUSEHOLDREGION, "houseHoldName");
alias.put(ExcelConstants.LOCALITYREGION, "localityName");
alias.put(ExcelConstants.CARDNUM, "cardNum");
alias.put(ExcelConstants.NOTARY, "notary");
alias.put(ExcelConstants.USE_COUNTRY, "use_country");
alias.put(ExcelConstants.LANGUAGE, "language");
alias.put(ExcelConstants.AUTH_NUM, "auth_num");
alias.put(ExcelConstants.USE, "use");
alias.put(ExcelConstants.REMARK, "remark");
excelReader.setHeaderAlias(alias);
List<ExcelOrderDTO> list = excelReader.readAll(ExcelOrderDTO.class);
return "success";
} catch (IOException e) {
SYS_LOGGER.error("excel解析异常",e);
return "failure";
}
}