“POI 工具类,Excel的快速导入导出,Excel模板导出,Word模板导出,可以仅仅5行代码就可以完成Excel的导入导出,修改导出格式简单粗暴,快速有效,easypoi值得你尝试”
目前来说,Easypoi确实方便,官网也提供了三种不同的版本,它在开源中国还,还是非常出名的,用的人非常多,也是对他的一个认可。
小编目前的项目,也是用这个来做,今天我们来做个excel的导入导出例子,看看怎么使用?
包体引入
目前官方提供最新版本是4.2.0,但是我在使用过程中,总是报错,时间关系就没怎么去查找,有兴趣的同学可以呀研究一下,类找不到,这个是apache的一个类,估计是新版本需要引入别的包,没去仔细追究。
1 java.lang.NoClassDefFoundError: org/apache/poi/xssf/usermodel/XSSFWorkbook
1 <!-- springboot核心web --> 2 <dependency> 3 <groupId>org.springframework.boot</groupId> 4 <artifactId>spring-boot-starter-web</artifactId> 5 </dependency> 6 7 <!-- 引入EasyPoi包 --> 8 <dependency> 9 <groupId>cn.afterturn</groupId> 10 <artifactId>easypoi-spring-boot-starter</artifactId> 11 <version>4.1.0</version> 12 </dependency> 13 14 <dependency> 15 <groupId>commons-fileupload</groupId> 16 <artifactId>commons-fileupload</artifactId> 17 <version>1.4</version> 18 </dependency>
编写导入导出工具类
1 public enum ExcelTypeEnum { 2 3 XLS("xls"), XLSX("xlsx"); 4 private String value; 5 private ExcelTypeEnum(String value) { 6 this.value = value; 7 } 8 public String getValue() { 9 return value; 10 } 11 public void setValue(String value) { 12 this.value = value; 13 } 14 }
1 /** 2 * Excel导出工具类 3 * @date:2020年5月29日 4 */ 5 @Component 6 public class ExcelExportUtils { 7 8 @Autowired 9 private HttpServletResponse response; 10 11 /** 12 * 导出excel 13 * @param list 泛型数据 14 * @param title 标题 15 * @param sheetName sheet的名称 16 * @param pojoClass 需要导出的对象 17 * @param fileName 文件名称 18 * @param isCreateHeader 是否创建表头 19 * @throws IOException void 20 */ 21 public void exportExcel(List<?> list, Class<?> pojoClass, String title, String sheetName, String fileName, 22 boolean isCreateHeader) throws IOException { 23 final ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF); 24 exportParams.setCreateHeadRows(isCreateHeader); 25 baseExport(list, pojoClass, fileName, exportParams); 26 } 27 28 /** 29 * 导出excel 30 * @param list 泛型数据 31 * @param title 标题 32 * @param sheetName sheet的名称 33 * @param pojoClass 需要导出的对象 34 * @param fileName 文件名称 35 * @param response 36 * @throws IOException void 37 */ 38 public void exportExcel(List<?> list, Class<?> pojoClass, String title, String sheetName, String fileName) 39 throws IOException { 40 baseExport(list, pojoClass, fileName, new ExportParams(title, sheetName, ExcelType.XSSF)); 41 } 42 43 /** 44 * 导出excel 45 * @param list 泛型数据 46 * @param pojoClass 需要导出的对象 47 * @param fileName 文件名称 48 * @param exportParams 文件书香 49 * @param response 50 * @throws IOException void 51 */ 52 public void exportExcel(List<?> list, Class<?> pojoClass, String fileName, ExportParams exportParams) 53 throws IOException { 54 baseExport(list, pojoClass, fileName, exportParams); 55 } 56 57 /** 58 * 多个sheet导出 59 * @param list 60 * @param fileName 61 * @throws IOException void 62 */ 63 public void exportExcel(List<Map<String, Object>> list, String fileName) throws IOException { 64 baseExport(list, fileName); 65 } 66 67 /** 68 * 最基础的对象导出 69 * @param list 数据列表 70 * @param pojoClass 导出对象 71 * @param fileName 文件名称 72 * @param exportParams 导出文件属性 73 * @throws IOException void 74 */ 75 private void baseExport(List<?> list, Class<?> pojoClass, String fileName, ExportParams exportParams) 76 throws IOException { 77 final Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list); 78 downLoadExcel(fileName, workbook); 79 } 80 81 /** 82 * 最基础的多sheet导出 83 * @param list 多个不同数据对象的列表 84 * @param fileName 文件名称 85 * @throws IOException void 86 */ 87 private void baseExport(List<Map<String, Object>> list, String fileName) throws IOException { 88 final Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF); 89 downLoadExcel(fileName, workbook); 90 } 91 92 /** 93 * 文件下载 94 * @param fileName 文件名称 95 * @param workbook exce对象 96 * @throws IOException void 97 */ 98 private void downLoadExcel(String fileName, Workbook workbook) throws IOException { 99 ServletOutputStream output = null; 100 try { 101 final String downloadName = URLEncoder.encode(fileName + "." + ExcelTypeEnum.XLSX.getValue(), "UTF-8"); 102 response.setCharacterEncoding("UTF-8"); 103 response.setHeader("content-Type", "application/vnd.ms-excel"); 104 response.setHeader("Content-Disposition", "attachment;filename=" + downloadName); 105 output = response.getOutputStream(); 106 workbook.write(output); 107 } 108 catch (final Exception e) { 109 throw new IOException(e.getMessage()); 110 } 111 finally { 112 if (output != null) { 113 output.flush(); 114 output.close(); 115 } 116 } 117 } 118 }
1 /** 2 * Excel导入工具类 3 * @date:2020年5月29日 4 */ 5 @Component 6 public class ExcelImportUtils { 7 8 /** 9 * 从指定位置获取文件后进行导入 10 * @param filePath 文件路径 11 * @param titleRows 表格标题行数,默认0 12 * @param headerRows 表头行数,默认1 13 * @param pojoClass 上传后需要转化的对象 14 * @return 15 * @throws IOException List<T> 16 */ 17 public <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) 18 throws Exception { 19 if (Strings.isEmpty(filePath)) { 20 return null; 21 } else { 22 final ImportParams params = new ImportParams(); 23 // 表格标题行数,默认0 24 params.setTitleRows(titleRows); 25 // 表头行数,默认1 26 params.setHeadRows(headerRows); 27 // 是否需要保存上传的Excel 28 params.setNeedSave(true); 29 // 保存上传的Excel目录 30 params.setSaveUrl("/excel/"); 31 return ExcelImportUtil.importExcel(new File(filePath), pojoClass, params); 32 } 33 } 34 35 /** 36 * 上传文件导入 37 * @param file 38 * @param titleRows 标题行 39 * @param headerRows 表头行 40 * @param needVerfiy 是否检验excel内容 41 * @param pojoClass 导入的对象 42 * @return 43 * @throws Exception List<T> 44 */ 45 public <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, boolean needVerfiy, 46 Class<T> pojoClass) throws Exception { 47 if (file == null) { 48 return null; 49 } else { 50 return baseImport(file.getInputStream(), titleRows, headerRows, needVerfiy, pojoClass); 51 } 52 53 } 54 55 /** 56 * 最基础导入 57 * @param inputStream 58 * @param titleRows 表格标题行数,默认0 59 * @param headerRows 表头行数,默认1 60 * @param needVerify 是否需要检测excel 61 * @param pojoClass 导入的对象 62 * @return 63 * @throws IOException List<T> 64 */ 65 private <T> List<T> baseImport(InputStream inputStream, Integer titleRows, Integer headerRows, 66 boolean needVerify, Class<T> pojoClass) throws Exception { 67 if (inputStream == null) { 68 return null; 69 } else { 70 final ImportParams params = new ImportParams(); 71 params.setTitleRows(titleRows); 72 params.setHeadRows(headerRows); 73 params.setSaveUrl("/excel/"); 74 params.setNeedSave(true); 75 params.setNeedVerify(needVerify); 76 return ExcelImportUtil.importExcel(inputStream, pojoClass, params); 77 } 78 79 } 80 }
编写导入导出对象
这里,为了覆盖更全一点,我分别用了不同的类型来做实验,数字类型采用NumberFormat进行格式化操作。
1 /** 2 * 用户信息 3 */ 4 public class User implements Serializable { 5 6 // 数字格式化 7 private NumberFormat nf = NumberFormat.getNumberInstance(); 8 9 private static final long serialVersionUID = 1L; 10 11 @Excel(name = "用户id", orderNum = "0", width = 15) 12 @Setter 13 @Getter 14 private long userId; 15 16 @Excel(name = "性别", orderNum = "1", width = 15, replace = { "男_1", "女_2" }, suffix = "孩") 17 @Setter 18 @Getter 19 private int sex; 20 21 @Excel(name = "金钱", orderNum = "2", width = 15) 22 @Setter 23 private double money; 24 25 public String getMoney() { 26 return nf.format(money); 27 } 28 29 @Excel(name = "用户信息", orderNum = "3", width = 15) 30 @Setter 31 @Getter 32 private String userName; 33 34 @Excel(name = "价格", orderNum = "4", width = 15) 35 @Setter 36 @Getter 37 private float price; 38 39 @Excel(name = "时间", orderNum = "5", width = 15, format = "yyyy-MM-dd") 40 @Setter 41 @Getter 42 private Date now; 43 }
编写测试方法
1 /** 2 * excel导入导出 3 * @date:2020年5月29日 4 */ 5 @Api(tags = { "APP服务:数据接口" }) 6 @RestController 7 @RequestMapping("view/ie") 8 public class ImportExportController { 9 10 @Autowired 11 private ExcelExportUtils excelExportUtils; 12 13 @Autowired 14 private ExcelImportUtils excelImportUtils; 15 16 /** 17 * 导出用户信息 18 */ 19 @ApiOperation(value = "导出excel") 20 @GetMapping(value = "/exportExcel") 21 public void exportExcel() throws Exception { 22 final List<User> userList = new ArrayList<>(); 23 for (int i = 0; i < 10; i++) { 24 final User user = new User(); 25 user.setUserId(i); 26 user.setSex(1); 27 user.setMoney(12332123 + i); 28 user.setUserName("小明" + i); 29 user.setPrice(23.1f + i); 30 user.setNow(new Date()); 31 userList.add(user); 32 } 33 excelExportUtils.exportExcel(userList, User.class, "用户信息", "员工信息的sheet", "用户信息表"); 34 } 35 36 /** 37 * 导入用户信息 38 * @param file 39 * @return 40 * @throws IOException Object 41 */ 42 @ApiOperation(value = "导入excel") 43 @GetMapping(value = "/importExcel") 44 public ResponseMsg<List<User>> importExcel(@RequestParam("file") MultipartFile file) throws Exception { 45 final List<User> userList = excelImportUtils.importExcel(file, 1, 1, false, User.class); 46 return MsgUtils.buildSuccessMsg(userList); 47 } 48 }
导出结果
在导出中,直接在浏览器输入地址接口,结果如截图所示
其中,金钱,时间上,我们分别进行了格式化