jydm

因为我们做的是前后端分离项目 无法采用response.write直接将文件流写出

我们采用阿里云oss 进行保存 再返回的结果对象里面保存我们的文件地址

废话不多说,上代码

Springboot

第一步导入poi相关依赖

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi</artifactId>
  <version>4.1.2</version>
</dependency>
<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi-ooxml</artifactId>
   <version>4.1.2</version>
</dependency>
<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi-ooxml-schemas</artifactId>
   <version>4.1.2</version>
</dependency>

第二步编写批量导出api

student对象

@Data
public class StudentDto {
    @JsonDeserialize(using = LongJsonDeserializer.class)
    @JsonSerialize(using = LongJsonSerializer.class)
    private Long id;
    private String name;
    private String studentId;
    private String collegename;
    private int collegeId;
    private int classId;
    private String classname;
    private Integer role;
    private String email;
    private String phone;
}

阿里云oss文件上传的service(不会使用阿里云oss的可以查看 https://www.cnblogs.com/jydm/p/14745418.html)

    @Override
    public String uploadFileXlsx(InputStream inputStream, String own,String fileName) throws Exception {
        OSS ossClient = OssUtil.getossClient();
        //这里最好对文件路径或名字做一下处理,防止文件名或路径重复导致文件丢失或者被覆盖
        String url ="pm/"+own+"/"+fileName+".xlsx";
        //上传
        ossClient.putObject(OssProperies.BUCKET_NAME, url, inputStream);
        // 关闭OSSClient。
        ossClient.shutdown();
        return "https://"+OssProperies.BUCKET_NAME+"."+OssProperies.END_POINT+"/"+url;
    }

 

Controller

    @ApiOperation("导出学生信息")
    @PostMapping("/exportStudents")
    @RequiresRoles("admin")
    public Result exportStudents(@RequestBody String students){
//将前端传递的json数据转换为对象数组 JSONObject jsonObject
= JSONObject.parseObject(students); List<StudentDto> studentDtos = JSONObject.parseArray(jsonObject.getJSONArray("students").toJSONString(), StudentDto.class);
//创建excel工作表 Workbook workbook
=new XSSFWorkbook(); Sheet studentsheet = workbook.createSheet("学生信息表"); Row row = studentsheet.createRow(0); String[] title= {"学号","姓名","学院","班级","电话","邮箱"}; for (int i = 0; i < 6; i++) { Cell cell = row.createCell(i); cell.setCellValue(title[i]); } for (int i = 1; i < studentDtos.size()+1; i++) { StudentDto studentDto = studentDtos.get(i - 1); Row row1 = studentsheet.createRow(i); Cell cell0 = row1.createCell(0); cell0.setCellValue(studentDto.getStudentId()); Cell cell1 = row1.createCell(1); cell1.setCellValue(studentDto.getName()); Cell cell2 = row1.createCell(2); cell2.setCellValue(studentDto.getCollegename()); Cell cell3 = row1.createCell(3); cell3.setCellValue(studentDto.getClassname()); Cell cell4 = row1.createCell(4); cell4.setCellValue(studentDto.getPhone()); Cell cell5 = row1.createCell(5); cell5.setCellValue(studentDto.getEmail()); } InputStream excelStream = null; String path=null; try {
//这里就是io流的转换 WorkBook需要写入一个输出流 阿里云oss保存文件需要一个输入流 ByteArrayOutputStream out
= new ByteArrayOutputStream(); workbook.write(out); out.close(); excelStream= new ByteArrayInputStream(out.toByteArray()); workbook.close();
path
= fileService.uploadFileXlsx(excelStream, "admin", "学生信息表"); } catch (Exception e) { e.printStackTrace(); } HashMap<Object, Object> map = new HashMap<>(); map.put("url",path); return Result.succ(map); }

这样我们就返回给前端我们的一个文件地址

vue前端处理

我们请求完成之后可以设置一个弹出框 询问用户是否需要下载 然后将 window.location.href 指向我们的文件地址

或者请求结果返回为请求成功,直接将window.location.href 指向我们的文件地址

async exportExcel(){
    const{data:res}=await  this.$axios.post("/student/exportStudents",{students:this.multipleSelection})
    console.log(res)
    if(res.code==200){
       this.$confirm('导出成功,是否下载到电脑', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success'
        }).then(() => {
       window.location.href=res.data.url
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });          
        });
    }
 }

 这样我们就实现了 springboot+vue前后端分离项目 批量导出功能

附阿里云oss购买渠道 https://www.aliyun.com/activity/1111?userCode=8crnx4b5 

 

相关文章: