批量导出Excel
前端代码
<el-button type="success" style="margin-left: 10px;" @click="exp()">导出报表</el-button>
//方法
exp(){
location.href = 'http://localhost:8080/type/export'
}
需要依赖
<!-- 国产工具类 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.0.M4</version>
</dependency>
<!-- 导入导出依赖 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
后台接口
@GetMapping("/export")
public Result export(HttpServletResponse response) throws IOException {
//1.思考
//要一行一行的组装数据,塞到一个list里面
//每一行数据,其实就对应数据库表中的一行数据,也就是对应java的中的实体类Type
//我们怎么知道某一列就是对应某一个表头呢?? 需要映射数据 需要Map map塞到list里面 key-value
//2.干
//1.从数据库中查询出所有的数据
List<Type> all = typeService.findAll();
if (CollectionUtil.isEmpty(all)) {//判断是否为空
//抛出异常
System.out.println("未找到数据");
}
//2.定义一个List 存储处理之后的数据,用于塞到list里
List<Map<String, Object>> list = new ArrayList<>(all.size());
//3.定义 Map<Key,Values>出来 遍历每一条数据,然后封装到Map<Key,Values>里,把这个map塞到list里
for (Type type : all) {
Map<String, Object> row = new HashMap<>();
row.put("分类名称", type.getName());
row.put("分类描述", type.getDescription());
list.add(row);
}
//4.创建一个ExcelWriter,把list 数据用writer写出来(生成出来)
ExcelWriter wr = ExcelUtil.getWriter(true);
wr.write(list, true);//把key做为一个头
//5.把这个excel 下载下来
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=type.xlsx");
ServletOutputStream out = response.getOutputStream();
wr.flush(out,true);
wr.close();
IoUtil.close(System.out);
return Result.success();
}
批量导入
前端代码
<el-upload style="display: inline-block;margin-left: 10px;" action="http://localhost:8080/type/upload" :show-file-list="false" :on-success="successUpload">
<el-button size="small" type="primary">批量导入</el-button>
</el-upload>
//方法
successUpload(res){
if (res.code === '0') {
this.$message.success("导入成功");
this.findBySearch();
}
}
后台接口
@PostMapping("/upload")
public Result upload(MultipartFile file) throws IOException {
//readAll(Type.class)读全部的数据映射Type类型
List<Type> infoList = ExcelUtil.getReader(file.getInputStream()).readAll(Type.class);
if (!CollectionUtil.isEmpty(infoList)) {
for (Type type : infoList) {
try {
typeService.add(type);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return Result.success();
}
实体类
@Alias("分类名称")
@Column(name = "name")
private String name;
@Alias("分类描述")
@Column(name = "description")