Hutool 之 Excel导入导出
前言
详情见官方文档https://hutool.cn/docs/#/poi/Excel%E5%B7%A5%E5%85%B7-ExcelUtil
依赖
<!-- Hutool poi 工具 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-poi</artifactId>
<version>5.7.22</version>
</dependency>
<!-- poi-ooxml 必须的依赖,不然会报错-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
导出
简单后端代码
/**
* Excel导出功能
* @param response
* @throws IOException
*/
@GetMapping("/export")
public void export(HttpServletResponse response) throws IOException {
//从数据库查询出所有的数据
List<User> list = userService.getUser();
//通过工具类创建writer写出到磁盘路径
// ExcelWriter writer = ExcelUtil.getWriter(filesUpLoadPath+"/用户信息.xlsx");
//在内存操作,写出到浏览器
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();
}
前端页面JS代码
handleExportExcel(){
window.open("http://localhost:9090/users/import")
}
导入
后端简单代码
/**
* Excel导入功能
* @param file
* @return
* @throws IOException
*/
@PostMapping("/import")
public boolean Import(MultipartFile file) throws IOException {
InputStream inputStream = file.getInputStream();
ExcelReader reader = ExcelUtil.getReader(inputStream);
//方式(1): 通过javabean的方式读取Excel内的对象,但是要求表头必须是英文,跟javabean的属性要对应起来
List<User> lists = reader.readAll(User.class);
//方式(2): 忽略表头的中文,直接读取表的内容
// List<List<Object>> list = reader.read(1);
// List<User> lists = 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());
// lists.add(user);
// }
//因为没有写批量新增方法,所以这里将list里面的数据遍历然后调用insert方法进行新增
for (User users : lists) {
userService.insert(users);
}
return true;
}
前端页面JS代码
<el-upload
class="upload-demo"
action="http://localhost:9090/users/import" :show-file-list="false" accept=".xlsx" :on- success="handleExcelImportSuccess" style="display: inline-block">
<el-button type="primary">导入<i class="el-icon-download"></i> </el-button>
</el-upload>
<script>
handleExcelImportSuccess(){
this.$message.success("导入成功!")
this.load()
}
</script>