JS导出Excel

两种方法都是网上搜索而来,项目中因为需求不一样两种方法都有使用,(注:Microsoft Edge浏览器导出无反应)

其一:导出当前网页内table表格

没有分页的情况下,导出当前页的table

click事件调用方法:tableToExcel('tableID','excel下载');
// tableId 传的值为table的id,fileName传的值为下载文件的文件名
tableToExcel(tableId,fileName){
                var hiddens = document.querySelectorAll("td.hidden");
                for(var i=0;i<hiddens.length;i++) {
                hiddens[i].parentNode.removeChild(hiddens[i]);
                }
                var nones = document.querySelectorAll("td.none");
                for(var j=0;j<nones.length;j++) {
                nones[j].parentNode.removeChild(nones[j]);
                }
                var table = document.getElementById(tableId);
                var excelContent = table.innerHTML;

                var excelFile = "<!DOCTYPE html><html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>";
                excelFile += "<head><meta charset='UTF-8'><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>"+fileName+"</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head>";
                excelFile += "<body><table>";
                excelFile += excelContent;
                excelFile += "</table></body>";
                excelFile += "</html>";
                var link = "data:application/vnd.ms-excel;base64," + this.base64(excelFile);
                var a = document.createElement("a");
                a.download = fileName+".xls";
                a.href = link;
                a.click();
},

其二:导出的表格数据直接调接口返回的数据

有分页的情况下,后台返回全部数据

// http为封装的axios.create方法,拦截验证token
import http from '@/utils/http'

/** 
 * 导出Excel
 * dataURL 导出接口+参数
 * */ 

export function exportRate(dataURL) {
    return http({
      url: dataURL,
      method: 'get',
      responseType: 'blob',  //二进制流
    })
}


// exportRate是封装的一个请求方法

let dataURL = '接口url+拼接'
exportRate(dataURL).then(res => {
         const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
         const downloadElement = document.createElement('a')
         const href = window.URL.createObjectURL(blob)
         downloadElement.href = href
         downloadElement.download = '下载.xls'
         document.body.appendChild(downloadElement)
         downloadElement.click()
         document.body.removeChild(downloadElement) // 下载完成移除元素
         window.URL.revokeObjectURL(href) // 释放掉blob对象
 })

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值