@Controller
@RequestMapping("/import")
public class ImportController extends BaseController {
@Autowired
private IEmployeeService employeeService;
@Autowired
private IDepartmentService departmentService;
@Autowired
private EmployeeExcelVerifyHandler employeeExcelVerifyHandler;
@RequestMapping("/index")
public String index(){
return "import";
}
@RequestMapping("/employeeXlsx")
public String employeeXlsx(MultipartFile empFile, HttpServletResponse response) throws Exception {
//一.使用EasyPoi获取文件数据
ImportParams params = new ImportParams();
params.setHeadRows(1);
params.setNeedVerfiy(true); //设置验证支持
params.setVerifyHandler(employeeExcelVerifyHandler); //设置一个验证处理器
//二.获取excel中的数据,封装成了一个结果对象(有很多东西)
ExcelImportResult result = ExcelImportUtil.importExcelMore(
empFile.getInputStream(),
Employee.class, params);
//三.获到正确的数据,并把它们保存到数据库
List list = result.getList();
list.forEach(e->{
e.setPassword("123");
Department dept = departmentService.findByName(e.getDepartment().getName());
e.setDepartment(dept);
employeeService.save(e);
});
//四.如果有错误,把错误数据返回到前台(让前台下载一个错误的excel)
//4.1判断是否有错误
if(result.isVerfiyFail()){
//4.2拿到错误的文件薄
Workbook failWorkbook = result.getFailWorkbook();
//把这个文件导出
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); //mime类型
response.setHeader("Content-disposition", "attachment;filename=error.xlsx"); //告诉浏览下载的是一个附件,名字叫做error.xlsx
response.setHeader("Pragma", "No-cache");//设置不要缓存
OutputStream ouputStream = response.getOutputStream();
failWorkbook.write(ouputStream);
ouputStream.flush();
ouputStream.close();
}
return "import";
}
}