两种方法都是网上搜索而来,项目中因为需求不一样两种方法都有使用,(注: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对象
})