excel文件下载demo案例

2022-06-14 16:50:33 浏览数 (1)

实际项目中excel文件下载是一个非常常见的功能,对于这个部分功能来做一个整理

代码语言:javascript复制
   <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>

后端代码

代码语言:javascript复制
 @GetMapping("/exportExcel")
    @ApiOperation("可根据查询条件导出excel")
    public void exportExcel(HttpServletResponse response,@RequestParam(value = "mntOrgName",required = false) String mntOrgName ) throws IOException {
        response.setCharacterEncoding("UTF-8");
        String orgId = FilterContextHandler.getOrgID();
        mntOrgName = mntOrgName == null ? null : mntOrgName.trim();
        List<MntOrg> list = mntTeamOrgService.searchAll(mntOrgName,orgId);
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("信息表");

        HSSFRow titleRow = sheet.createRow(0);
        // 设置单元格的宽度
        for (int i = 0; i < 4; i  ) {
            sheet.setColumnWidth(i, 9000);

        }

        titleRow.createCell(0).setCellValue("机构名称");
        titleRow.createCell(1).setCellValue("联系人电话");
        titleRow.createCell(2).setCellValue("传真");
        // titleRow.createCell(4).setCellValue("描述");
        for (MntOrg mntOrg : list) {
            HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum()   1);
            dataRow.createCell(0).setCellValue(mntOrg.getMntOrgName());
            dataRow.createCell(1).setCellValue(mntOrg.getContactNo());
            dataRow.createCell(2).setCellValue(mntOrg.getFax());
        }
        String filename = DateUtil.getNowDate()   ".xls";
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=" filename);
        OutputStream ouputStream = response.getOutputStream();
        wb.write(ouputStream);
        ouputStream.flush();
        ouputStream.close();
    }

vue前端代码

代码语言:javascript复制
download(){
          this.$axios.get('/exam/downloadVerifierTemplate', { responseType: "blob" }).then(res => {
          const fileName = "测试表格123.xlsx";  
          let nowDate = new Date()
       let date = {
       year: nowDate.getFullYear(),
       month: nowDate.getMonth()   1,
        date: nowDate.getDate()
  }
    this.systemTime = date.year   '-'   date.month   '-'   date.date
    console.log(this.systemTime)
        
          //   res.data:请求到的二进制数据 
          const blob = new Blob([res.data], { type: "application/vnd.ms-excel" }); //1.创建一个blob
          const link = document.createElement("a"); //2.创建一个a链接
          link.download = fileName; //3.设置名称
          link.style.display = "none"; // 4.默认不显示
          link.href = URL.createObjectURL(blob); // 5.设置a链接href
          document.body.appendChild(link);//6.将a链接dom插入当前html中
          link.click();//7.点击事件
          URL.revokeObjectURL(link.href); //8.释放url对象
          document.body.removeChild(link); //9.移除a链接dom
      });
     }

0 人点赞