后台接口返回void但是response有设置合适的相关信息,前端调用接口解析Blob数据下载excel文件

1、pom.xml文件增加依赖:

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

2、接口代码如下:

复制代码
/**
     * 企业列表--导出
     */
    @GetMapping(value = "/downloadTenantList")
    public void downloadTenantList(HttpServletRequest request,HttpServletResponse response) {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        Workbook wb = new SXSSFWorkbook(500);
        Sheet sheet = wb.createSheet();
        wb.setSheetName(0,"企业");
        Row titleRow1 = sheet.createRow(0);
        titleRow1.setHeightInPoints(30);
        Cell titleCellID = titleRow1.createCell(0);
        titleCellID.setCellValue("ID");
        Cell titleCellName = titleRow1.createCell(1);
        titleCellName.setCellValue("名称");

        Row titleRow2 = sheet.createRow(1);
        titleRow2.setHeightInPoints(30);
        Cell valCellID2 = titleRow2.createCell(0);
        valCellID2.setCellValue("ID");
        Cell valCellName2 = titleRow2.createCell(1);
        valCellName2.setCellValue("名称");
        try
        {
            wb.write(response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("导出企业Excel异常{}", e.getMessage());
        }
        finally
        {
            IOUtils.closeQuietly(wb);
        }
    }

3、前端代码如下,可以作为参考,但需要根据实际情况整理

复制代码
import { saveAs } from 'file-saver'
function blobValidate(data) {
  return data.type !== 'application/json'
}
/**
* 参数处理
* @param {*} params  参数
*/
export function tansParams(params) {
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    var part = encodeURIComponent(propName) + "=";
    if (value !== null && value !== "" && typeof (value) !== "undefined") {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
            let params = propName + '[' + key + ']';
            var subPart = encodeURIComponent(params) + "=";
            result += subPart + encodeURIComponent(value[key]) + "&";
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return result
}
export function download(url, params, filename, config) {
  downloadLoadingInstance = Loading.service({ text: "正在下载数据,请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
  return service.post(url, params, {
    transformRequest: [(params) => { return tansParams(params) }],
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    responseType: 'blob',//使用这个或者{responseType:'arraybuffer'}
    ...config
  }).then(async (data) => {
    const isBlob = blobValidate(data);
    if (isBlob) {
      const blob = new Blob([data])
      saveAs(blob, filename)
    } else {
      const resText = await data.text();
      const rspObj = JSON.parse(resText);
      const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
      Message.error(errMsg);
    }
    downloadLoadingInstance.close();
  }).catch((r) => {
    console.error(r)
    Message.error('下载文件出现错误,请联系管理员!')
    downloadLoadingInstance.close();
  })
}

这样就可以通过调用接口的方式导出excel文件,请求接口就可以在header中设置认证头

相关推荐
林强1812 小时前
前端文件预览docx、pptx和xlsx
前端
一路向北⁢2 小时前
基于 Apache POI 5.2.5 构建高效 Excel 工具类:从零到生产级实践
java·apache·excel·apache poi·easy-excel·fast-excel
像是套了虚弱散4 小时前
DevEco Studio与Web联合开发:打造鸿蒙混合应用的全景指南
开发语言·前端·华为·harmonyos·鸿蒙
衬衫chenshan4 小时前
【CTF】强网杯2025 Web题目writeup
前端
飞翔的佩奇5 小时前
【完整源码+数据集+部署教程】【天线&水】舰船战舰检测与分类图像分割系统源码&数据集全套:改进yolo11-repvit
前端·python·yolo·计算机视觉·数据集·yolo11·舰船战舰检测与分类图像分割系统
哆啦A梦15886 小时前
点击Top切换数据
前端·javascript·vue.js
程序猿追6 小时前
Vue组件化开发
前端·html
艾德金的溪6 小时前
redis-7.4.6部署安装
前端·数据库·redis·缓存
小光学长7 小时前
基于Vue的2025年哈尔滨亚冬会志愿者管理系统5zqg6m36(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
前端·数据库·vue.js
@PHARAOH7 小时前
WHAT - 受控组件和非受控组件
前端·javascript·react.js