@GetMapping("/excel/upload")
public void importExcel(@RequestParam("excelFile") MultipartFile multipartFile) throws IOException {
if (multipartFile==null|| multipartFile.getSize()==0){
log.error("文件上传错误,重新上传");
}
String filename = multipartFile.getOriginalFilename();
if (!(filename.endsWith(".xls")|| filename.endsWith(".xlsx"))){
log.error("文件上传格式错误,请重新上传");
}
List<RuleVo> ruleVoList = readXLS(multipartFile);
System.out.println("完毕");
}
public List<RuleVo> readXLS(MultipartFile file) throws IOException {
List<RuleVo> ruleVoList =new ArrayList<>();
InputStream inputStream = file.getInputStream();
HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
//读取第一张sheet
HSSFSheet sheet = workbook.getSheetAt(0);
String errorMsg="";
//遍历每一行Excel获取内容
for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
HSSFRow row = sheet.getRow(rowNum);
if (row!=null){
RuleVo ruleVo = new RuleVo();
//使用了getStringCellValue()方法来获取值,POI会判断单元格的类型,如果非字符串类型就会抛出上面的异常。
//所以先使用setCellType()方法先将该单元格的类型设置为STRING
//然后poi会根据字符串读取它
row.getCell(0).setCellType(CellType.STRING);
HSSFCell cell = row.getCell(1);
//todo 有指针异常风险 row.getCell记得判断。
row.getCell(1).setCellType(CellType.STRING);
row.getCell(2).setCellType(CellType.STRING);
row.getCell(3).setCellType(CellType.STRING);
row.getCell(5).setCellType(CellType.STRING);
row.getCell(6).setCellType(CellType.STRING);
ruleVo.setName(row.getCell(0).getStringCellValue());
ruleVo.setGroupId(Long.parseLong(row.getCell(1).getStringCellValue()));
ruleVo.setChannel(row.getCell(2).getStringCellValue());
ruleVo.setVersion(Integer.parseInt(row.getCell(3).getStringCellValue()));
String ruleContentList = row.getCell(5).getStringCellValue();
RuleContent[] array = new Gson().fromJson(ruleContentList,RuleContent[].class);
List<RuleContent> list = Arrays.asList(array);
ruleVo.setContentList(list);
ruleVo.setOperator(row.getCell(6).getStringCellValue());
ruleVo.setCreateTime(row.getCell(7).getDateCellValue());
ruleVo.setUpdateTime(row.getCell(8).getDateCellValue());
ruleVoList.add(ruleVo);
}
}
return ruleVoList;
}