话不多说,直接上代码
依赖文档
找到pom文件,如下图所示
引入需要的依赖
<!-- hutool--><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.7.20</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version></dependency>
导出写法:
@GetMapping("/export")public void export(HttpServletResponse response) throws Exception {// 从数据库查询出所有的数据List<User> list = userService.list();// 左内存操作,写出到浏览器ExcelWriter writer = ExcelUtil.getWriter(true);// 自定义标题别名writer.addHeaderAlias("username", "用户名");writer.addHeaderAlias("password", "密码");writer.addHeaderAlias("nickname", "昵称");writer.addHeaderAlias("email", "邮箱");writer.addHeaderAlias("phone", "电话");writer.addHeaderAlias("address", "地址");writer.addHeaderAlias("createTime", "创建时间");// 一次性写出list内的对象到Excel,使用默认样式,强制输出标题writer.write(list, true);// 设置浏览器响应的格式response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");String fileName = URLEncoder.encode("用户信息", "UTF-8");response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");ServletOutputStream out = response.getOutputStream();writer.flush(out, true);out.close();writer.close();}
导入写法:
// export 导入@PostMapping("/import")public Result imp(MultipartFile file) throws Exception {InputStream inputStream = file.getInputStream();ExcelReader reader = ExcelUtil.getReader(inputStream);reader.addHeaderAlias("用户名", "username");reader.addHeaderAlias("密码", "password");reader.addHeaderAlias("昵称", "nickname");reader.addHeaderAlias("邮箱", "email");reader.addHeaderAlias("电话", "phone");reader.addHeaderAlias("地址", "address");List<User> list = reader.readAll(User.class);return Result.success(userService.saveBatch(list), "'返回成功'");}
已上就是导入导出