简单的导入导出 封装 ,大家都说超级好用
上来就是梭哈
工具类如下:
/**
* Author: lyc
* Date: 2020/6/15 16:27
*/
@Slf4j
public class ExcelUtils {
/**
* 导出
* @param response
* @param fileName
* @param rows
*/
public static void exportExcel(HttpServletResponse response, String fileName, List<Map> rows){
Assert.isBlank(fileName,"文件名不能为空");
ExcelWriter writer = cn.hutool.poi.excel.ExcelUtil.getWriter();
writer.write(rows, true);
response.setContentType("application/vnd.ms-excel;charset=utf-8");
try {
response.setHeader("Content-Disposition","attachment;filename="+new String(fileName.getBytes(), "ISO-8859-1")+".xlsx");
} catch (UnsupportedEncodingException e) {
log.error("编码格式不支持");
}
ServletOutputStream out= null;
try {
out = response.getOutputStream();
writer.flush(out);
writer.close();
} catch (IOException e) {
log.error("导出文件错误",e);
}finally {
IoUtil.close(out);
}
}
/**
* 导出
* @param file
* @return
*/
public static List<Map<String, Object>> importExcel(MultipartFile file) {
ExcelReader reader = null;
try {
reader = cn.hutool.poi.excel.ExcelUtil.getReader(file.getInputStream());
List<Map<String,Object>> readAll = reader.readAll();;
return readAll;
} catch (IOException e) {
log.error("导入文件错误",e);
}
return null;
}
}
demo 如下:
@RequestMapping("user/export")
public void exportUser(HttpServletResponse httpServletResponse){
List<User> list = userService.list();
List<Map> rows = Lists.newArrayList();
list.forEach(e->{
Map row = new HashMap();
row.put("姓名",e.getName());
row.put("年龄",e.getAge());
rows.add(row);
});
ExcelUtils.exportExcel(httpServletResponse,"用户列表",rows);
}
@RequestMapping("user/import")
public Result importUser(MultipartFile file){
List<Map<String, Object>> mapList = ExcelUtils.importExcel(file);
List<User> userList = Lists.newArrayList();
mapList.forEach(e->{
String name = String.valueOf(e.get("姓名"));
Integer age = Integer.parseInt(String.valueOf(e.get("年龄")));
User user = new User();
user.setId(1);
user.setAge(age);
user.setName(name);
userList.add(user);
});
userService.saveBatch(userList);
return Result.ok();
}
测试 如下:
elk