话不多说,直接上代码
依赖文档
找到pom文件,如下图所示
引入需要的依赖文章来源:https://www.toymoban.com/news/detail-701437.html
<!-- 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), "'返回成功'");
}
已上就是导入导出文章来源地址https://www.toymoban.com/news/detail-701437.html
到了这里,关于SpringBoot实现Excel导入导出的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!