Multi-sheet import is similar to simple import, except that the controller layer is slightly different.
For other codes, click Excel of Easypoi to simply import
the controller layer code.
/**
* 多sheet导入Excel数据
*/
@RequestMapping(value = "multImports",method = RequestMethod.POST)
@ResponseBody
public String multImports(MultipartFile file) throws IOException {
if (null==file){
return GetResult.getResultObj("文件上传失败");
}
//根据file得到Workbook,主要是要根据这个对象获取,传过来的excel有几个sheet页
Workbook hssfWorkbook = getWorkBook(file);
//获取sheet数量
int sheetNum = hssfWorkbook.getNumberOfSheets();
ImportParams params = new ImportParams();
//表头在第几行
params.setTitleRows(5);
try {
List<Applys> list = new ArrayList<>();
for (int sheetIndex = 0; sheetIndex < sheetNum; sheetIndex++) {
//第几个sheet页
params.setStartSheetIndex(sheetIndex);
List<Applys> result = ExcelImportUtil.importExcel(file.getInputStream(), Applys.class, params);
list.addAll(result);
}
for (int i = 0; i < list.size(); i++) {
if (null==list.get(i).getRealName()){
list.remove(i);
i--;
}
}
if (list.size()==0){
return GetResult.getResultObj("数据读取失败,检查Excel数据格式");
}
if (ApplyService.saveBatch(list)){
return GetResult.getResultObj("ok");
}
} catch (Exception e) {
e.printStackTrace();
}
return GetResult.getResultObj("文件读取失败");
}
/**
* 获取Excel中的sheet
* @param file
* @return
* @throws IOException
*/
public static Workbook getWorkBook(MultipartFile file) throws IOException {
//这样写excel能兼容03和07
InputStream is = file.getInputStream();
Workbook hssfWorkbook = null;
try {
hssfWorkbook = new HSSFWorkbook(is);
} catch (Exception ex) {
is =file.getInputStream();
hssfWorkbook = new XSSFWorkbook(is);
}
return hssfWorkbook;
}