前端导出文档的方式


  1、后台处理,返回链接的方式

数据、文件格式全部在后台封装好,返回给前端一个链接,前端通过点击链接自动下载,两种方式:

  window.location.href = ‘url’
  'url' download=''>

   2、解析后台返回的文件流

这种方式就是后台将要导出的文件以文件流的方式返回给前端,前端通过blob去解析,再动态创建a标签。

// 发请求
this.axios.post(url, {param: paramName}, {responseType: 'arraybuffer'}).then(res => {
    let content = res.data; // 文件流
    let blob = new Blob([content],{type: 'application/octet-stream'});
    let fileName = 'filename.xls';
    // 如果后端返回文件名
    // let contentDisposition = res.headers['content-disposition'];
    // let fileName = decodeURI(contentDisposition.split('=')[1]);
        if ('download' in document.createElement('a')) {  // 非IE下载
        let link = document.createElement('a');
        link.download = fileName;
        link.style.display = 'none';
        link.href = URL.createObjectURL(blob);
        document.body.appendChild(link);
        link.click();
        URL.revokeObjectURL(link.href) ; // 释放URL 对象
        document.body.removeChild(link);
    } else {  // IE10+下载
      navigator.msSaveBlob(blob,fileName);
    }
})

   3、接收数据,纯前端实现

这种方式就是后台只需提供对应的数据即可,前端动态生成表格数据,再格式化。
let excel = '';
// 生成表头
let row = '' +
  '' +
  '' +
  '' +
  '';
excel += row + '';
// 循环生成表身for(let i = 0 ; i < this.excelData.length ; i++ ){
  excel += '';
  for(let item inthis.excelData[i]){
    //增加\t为了不让表格显示科学计数法或者其他格式if (!this.excelData[i][item]) {
      this.excelData[i][item] = '';
    }
    excel +=``;
  }
  excel +='';
}
excel += '
标题1标题2标题3
${ this.excelData[i][item] + '\t'}
'; //下载的表格模板数据 var excelFile = '' + 'xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">'; excelFile += ''; excelFile += ''; excelFile += ' charset="UTF-8">'; excelFile += ''; excelFile += ''; excelFile += ''; excelFile += ''; excelFile += excel; excelFile += ''; excelFile += ''; //下载模板 let uri = 'data:application/vnd.ms-excelcharset=utf-8,' + encodeURIComponent(excelFile); let link = document.createElement('a'); link.href = uri; link.style = 'visibility:hidden'; let myDate = new Date(); let time = myDate.toLocaleDateString().split('/').join('-'); link.download = 'fileName' + time + '.xls'; document.body.appendChild(link); link.click(); document.body.removeChild(link);