对poi进行了封装,简化代码量,提高开发效率,避免出现大数据量下效率低甚至可能出现内存溢出的情况
仓库地址:https://gitee.com/lemur/easypoi
maven依赖:
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-spring-boot-starter</artifactId>
<version>4.3.0</version>
</dependency>
使用:
1.对需要用到的实体类字段添加注解@Excel
width设置宽度
日期可设置格式
2.导出
HSSF 03版本Excel .xls
XSSF 07版本Excel .xlsx
@ApiOperation("导出数据")
@GetMapping(value = "/export",produces = "application/octet-stream")
public void exportEmp(HttpServletResponse response){
//得到数据
List<Employee> employeeList = employeeService.list();
ExportParams params = new ExportParams("员工表", "员工表", ExcelType.HSSF);
Workbook workbook = ExcelExportUtil.exportExcel(params, Employee.class, employeeList);
ServletOutputStream outputStream=null;
try {
//流形式
response.setHeader("content-type","application/octet-stream");
//防止中文乱码
response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode("员工表.xls","UTF-8"));
outputStream = response.getOutputStream();
workbook.write(outputStream);
} catch (IOException e) {
e.printStackTrace();
}finally {
if (outputStream!=null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3.导入
@ApiOperation("导入数据")
@PostMapping("/import")
public ResultVo importEmp(MultipartFile file){
ImportParams params = new ImportParams();
//标题行
params.setTitleRows(1);
try {
List<Employee> list = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, params);
if (employeeService.saveBatch(list)){
return ResultVo.success("导入成功");
}
} catch (Exception e) {
e.printStackTrace();
}
return ResultVo.error("导入失败");
}