前后端分离springboot+vue2查询数据导出为Excel

后端添加POI依赖

xml 复制代码
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.2.3</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.2.3</version>
</dependency>
 

后端接口

复制代码
 // 条件导出流程
    @PostMapping({"/exportActivesByCondition"})
    public void exportActivesByCondition(@RequestBody Map<String, Object> paramMap, HttpServletResponse response) throws IOException {
       processService.exportActivesByCondition(paramMap, response);
    }

后端实现

复制代码
@Override
    public void exportActivesByCondition(Map<String, Object> paramMap, HttpServletResponse response) throws IOException {
        Process process = new Process();
        String formType = (String)paramMap.get("formType");
        process.setTitle(formType);
        process.setOrderId((String)paramMap.get("orderId"));
        String currentUsername = BaseContext.getCurrentUsername();
     
        // 查询数据
        List<Process> processList = processMapper.exportActivesByCondition(process, currentUsername);

        // 2. 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");

        String fileName = URLEncoder.encode("导出数据_" + System.currentTimeMillis(), "UTF-8")
                .replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition",
                "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 使用POI创建Excel
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("Sheet1");

        // 创建表头
        String[] headers = {"订单单号", "表单类型", "申请人", "流程状态"};
        XSSFRow headerRow = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            XSSFCell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }

        // 填充数据
        for (int i = 0; i < processList.size(); i++) {
            XSSFRow dataRow = sheet.createRow(i + 1);
            Process p = processList.get(i);
            dataRow.createCell(0).setCellValue(p.getOrderId());
            dataRow.createCell(1).setCellValue(p.getTitle());
            dataRow.createCell(2).setCellValue(p.getApplicant());
            dataRow.createCell(3).setCellValue(p.getStage());
        }

        // 输出
        workbook.write(response.getOutputStream());
        workbook.close();
    }

前端

复制代码
<el-button size="mini" @click="exportActives" :disabled="isSubmit">导出流程</el-button>

组件方法,放在 method方法内

复制代码
 // 导出进行中流程
    async exportActives() {
      this.isSubmit = true  // 禁用
      try {
        // console.log(this.Parameters.stage)
        const response = await reqExportActivesByCondition(this.queryParams)
        downloadExcel(response, `流程数据_${new Date().getTime()}.xlsx`)
        this.$message.success('导出成功')
      } catch (error) {
        this.$message.error('导出失败,请重试', error)
        this.isSubmit = false  // 取消禁用
      }
      this.isSubmit = false  // 取消禁用
    },

下载excel方法

复制代码
/**
 * 下载Excel文件
 */
export function downloadExcel(blob, fileName = `export_${Date.now()}.xlsx`) {
    // 创建下载链接
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.href = url
    link.download = fileName
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
}

请求接口,需要把相应类型设置为 blob。responseType: 'blob'

复制代码
// 条件导出流程
export function reqExportActivesByCondition(params) {
    return request({
        url: '/process/exportActivesByCondition',
        method: 'post',
        data:  params ,
        responseType: 'blob'
    })
}
相关推荐
codeGoogle5 小时前
自研 IM 还是选择第三方 SDK?企业开发者应该如何权衡?
前端·后端·程序员
许彰午7 小时前
在PowerBuilder里手写Excel导出——OLE控制Excel的完整方案
excel
DLYSB_7 小时前
API 网关流量洪峰与突发 CC 攻击:我用 Go 写了个“现场物理防御哨兵”,把故障响应压缩到秒级
开发语言·后端·golang·报警灯
markinmarkin8 小时前
Spring 中Bean 的作用域有哪些?
java·后端·spring
橙子家9 小时前
使用方法 ToDictionary() 来优化查询时间复杂度:O(N*M) -> O(1*M)【C# 基础】
后端
IT_陈寒9 小时前
我又被JavaScript的隐式类型转换坑了
前端·人工智能·后端
用户8356290780519 小时前
Python Word 转 PDF 和 PDF 转 Word 指南
后端·python
用户83562907805110 小时前
如何使用 Python 加密和保护 Word 文档
后端·python
他们叫我秃子10 小时前
前端开发转 Go 全栈(五):终于遇到熟人了,Go 的闭包和高阶函数原来这么像 JavaScript
前端·后端·go
SomeB1oody10 小时前
【RustyML入门】2.6. 线性判别分析
开发语言·后端·机器学习·rust·教程