前端通过后台返回的字符流导出excel表格

1.平时前端导出excel表格时简单的方式

window.location.href="后台接口地址";

2.有时候导出需要权限的时候,后台要求在导出的时候要在headers里面加token;这是第一种方式就不行了,一般我们会通过ajax,或者axios,或者其他的请求方式获取后台数据的时候统一处理headers里面的token;

具体代码,拿到后台返回的数据后

 const blob = new Blob([res], {  // res 为后台返回数据
          type: 'application/vnd.ms-excel;charset=utf-8', // 导出数据生成excel的格式设置
        });
        if ('download' in document.createElement('a')) {
          // 非IE下载
          const elink = document.createElement('a');
          elink.download = `${fileName}.xls`;
          elink.style.display = 'none';
          elink.target = '_blank';
          elink.href = window.URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
    }

3.还有一点需要注意,在获取到后台数据的时候,我们要设置一些接收后台数据类型格式

{
responseType: 'blob',
}

你可能感兴趣的:(前端通过后台返回的字符流导出excel表格)