Vue、SpringBoot 实现导出excel

1、添加依赖


        
            org.apache.poi
            poi-ooxml
            ${poi.version}
        

2、实体类添加Excel注解

@Excel(name = "设备ID")
private Long id;

3、前端

/** 导出按钮操作 */
    handleExport() {
      const queryParams = this.dataList;
      this.$confirm('是否确认导出所有数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/generator/pfac/export'),
          method: 'get',
        }).then(({data}) => {
       //上一个请求获得url地址,进行第二步操作
          if (data && data.code === 0) {
            window.location.href = this.$http.adornUrl("/common/download?fileName="+data.msg+"&delete=" + false);
          }
        })})
    }

4、后台处理请求(文件生成)

@GetMapping("/export")
    public R export(PFacEntity pFacEntity)
    {
        List list = pFacDao.selectList(null);
        ExcelUtil util = new ExcelUtil(PFacEntity.class);
        return util.exportExcel(list, "pFacEntity");
    }

return的结果:
{msg=da5dd983-37be-47d4-a505-ce0a6abdfc8b_pFacEntity.xlsx, code=0}

ExcelUtil工具类对查询结果进行封装生成文件,返回url


image.png

5、后台处理下载请求(文件下载)

@GetMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        System.out.println(fileName+"--name");
        try
        {
            if (!FileUtils.isValidFilename(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = "D:/ruoyi/" + fileName;
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            System.out.println("下载文件失败"+e);
        }

    }

你可能感兴趣的:(Vue、SpringBoot 实现导出excel)