“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 }
導出結果
在導出中,直接在瀏覽器輸入地址接口,結果如截圖所示
其中,金錢,時間上,我們分別進行了格式化