在实际项目开发中经常需要使用excel导入数据或导出数据到excel中,使用POI做开发有点麻烦,推荐大家一个特别好用的excel导入导出的组件,超级好用,gitee地址:https://gitee.com/wuwenze/ExcelKit
首先导入依赖
<dependency> <groupId>com.wuwenze</groupId> <artifactId>ExcelKit</artifactId> <version>2.0.72</version> <exclusions> <exclusion> <artifactId>xml-apis</artifactId> <groupId>xml-apis</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>xml-apis</groupId> <artifactId>xml-apis</artifactId> <version>1.4.01</version> </dependency>
特别说明:如果只是导入Excelkit包的话,可能xml-apis包版本太低而报错,所以从新高版本的xml-apis可以解决
创建实体类,配置exle与实体之间的映射关系
@Data @Excel(value = "用户信息") @AllArgsConstructor @NoArgsConstructor public class User { @ExcelField(value = "编号", width = 30) private Long userId; @ExcelField(value = "用户名",required = true) private String username; @ExcelField(value = "密码", required = true, maxLength = 32) private String password; @ExcelField(value = "邮箱",required = true, maxLength = 32 ) private String email; }
一行代码构建excel导入模板,创建controller类
@RestController @Slf4j public class ExcelController { /** * 下载excel模板 * * @param response */ @RequestMapping(value = "/downTemplate", method = RequestMethod.GET) public void downTemplate(HttpServletResponse response) { List<User> userList = new ArrayList<>(); ExcelKit.$Export(User.class, response).downXlsx(userList, true); } }
通过excel导入模板数据
@RequestMapping(value = "/importUser", method = RequestMethod.POST) public ResponseEntity<?> importUser(@RequestParam MultipartFile file) throws IOException { List<User> successList = Lists.newArrayList(); List<Map<String, Object>> errorList = Lists.newArrayList(); ExcelKit.$Import(User.class) .readXlsx( file.getInputStream(), new ExcelReadHandler<User>() { @Override public void onSuccess(int sheetIndex, int rowIndex, User entity) { successList.add(entity); // 单行读取成功,加入入库队列。 } @Override public void one rror(int sheetIndex, int rowIndex, List<ExcelErrorField> errorFields) { // 读取数据失败,记录了当前行所有失败的数据 Map<String, Object> errorMap = new HashMap<>(); errorMap.put("sheetIndex", sheetIndex); errorMap.put("rowIndex", rowIndex); errorMap.put("errorFields", errorFields); errorList.add(errorMap); } }); // TODO: 执行successList的入库操作。 HashMap<String, Object> resultMap = new HashMap<>(); resultMap.put("data", successList); resultMap.put("haveError", !CollectionUtil.isEmpty(errorList)); resultMap.put("error", errorList); return ResponseEntity.ok(resultMap); }