前后端分离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'
    })
}
相关推荐
moMo1 分钟前
LangChain 到 LangGraph: RAG 知识库改造
后端
用户574385305117 分钟前
元数据驱动的通用 CRUD 后端框架 (3- createBusiness 工厂:三层装配 + 一行出 REST)
后端
linmengmeng_131429 分钟前
【总结】MyBatis-Plus批量插入与清表的正确姿势
java·spring boot·mysql·mybatis
高级程序源29 分钟前
django大学生创新创业项目管理系统94923-计算机课程设计、毕业设计
javascript·vue.js·spring boot·后端·python·django·课程设计
Sam_Deep_Thinking35 分钟前
new Thread()之后发生了什么?
java·后端·面试·程序员
步行cgn1 小时前
Spring util 命名空间详解
java·后端·spring
打工仔折腾 AI2 小时前
普通摄像头接入AI识别:绿联NAS部署Frigate监控实战
人工智能·后端·python·性能优化·ai agent 实战
暮雨哀尘2 小时前
JAVA基础练习(四):SpringBoot 实现简易登录功能
java·spring boot·eclipse·maven
万物智能4 小时前
SARADC模数转换—【万物智能之开源鸿蒙OpenHarmony系统实战开发系列教程】
前端·后端