下载导出Excel

第一种:直接通过连接下载Excel

window.location.href = 'https://x.x.x.243/static/sample/template.xlsx';

 

第二种:后端返回文件流下载导出Excel

首先 axios需要设置 responseType: 'blob'

如果需要自定义下载文件名可以使用elementUI的组件;

完整代码如下:

public exportExcel () {
    this.$prompt(' ', 'Please enter the file name :', {
      confirmButtonText: 'confirm',
      cancelButtonText: 'cancel',
      inputPattern: /.*[^\s]/, //验证文件名不为空
      inputErrorMessage: 'illegal filename', //文件名不合规报错信息
      inputValue: `xxx-${this.nowDate}` //名字为xxx+现在时间
      // @ts-ignore 
    }).then(({ value }) => {
      let data = {
        method:'post', //请求方式
        url:'url/export', //请求地址
        fileName: value+'.xlsx', //文件名称,此处为上面的inputValue
        params: getNowDate('-') //参数
      }
      this.handleExportExcel(data);
    }).catch(() => {});
  }

  public async handleExportExcel(data:any){
    axios({
          method: data.method,
          url: data.url,
          data: data.params,
          responseType: 'blob'  //此处必须设置
      }).then((res) => {
  //以下为下载Excel的代码块流程
const link = document.createElement('a'); let blob = new Blob([res.data], {type: 'application/vnd.ms-excel;'}); link.style.display = 'none'; link.href = URL.createObjectURL(blob); link.download = data.fileName; document.body.appendChild(link); link.click(); document.body.removeChild(link); console.log(res)
}).
catch(error => { console.log('error') }); }

 

 
posted @ 2020-09-03 10:48  hannahY  阅读(313)  评论(0编辑  收藏  举报