不知道小伙伴们在写项目时有没有被导入导出这两个功能所困扰,今天在这里我就springboot+vue跟你们分享一下我看B站程序员青戈第13个视频关于导入导出的笔记,可能还有地方要完善,希望能给各位友友一点灵感。
一、安装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", "创建时间");
writer.addHeaderAlias("avatarUrl", "头像");
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();
}
- 开启后端,在浏览器上输入地址:localhost:8086/user/export,会将用户信息打印在excel表格中。效果如下:
三、后端导入
- 代码详情:
/**
* 导入接口
*/
@PostMapping("/import")
public Boolean imp(MultipartFile file) throws Exception {
InputStream inputStream = file.getInputStream();
ExcelReader reader = ExcelUtil.getReader(inputStream);
//表头要和javabean的一致
// List<User> list = reader.readAll(User.class);
// List<User> list = reader.read(0,1,User.class);
// userService.saveBatch(list);
//忽略表头的中文
List<List<Object>> list = reader.read(1);
List<User> users = CollUtil.newArrayList();
for (List<Object> row : list) {
User user = new User();
user.setUsername(row.get(0).toString());
user.setPassword(row.get(1).toString());
user.setNickname(row.get(2).toString());
user.setEmail(row.get(3).toString());
user.setPhone(row.get(4).toString());
user.setAddress(row.get(5).toString());
user.setAvatarUrl(row.get(6).toString());
users.add(user);
}
userService.saveBatch(users);
return true;
}
- 在Apifox测试导入接口,返回200,数据库成功导入数据
四、前后端导入导出功能
- 导入
- 导出
好了,以上就是我看第13个视频的学习笔记,希望对你们有帮助,我们下期再见!