思緒,js下載文件,不過就是天生base64,然後賦值給a標籤舉行導出下載
讀取文件excel的filetype:
var input = document.querySelector('input');
input.addEventListener('change',function(){
var file = this.files[0];
fileOtions.type = file.type;
var reader = new FileReader();
reader.onload = function(e){
console.log(e.target.result);
};
reader.readAsDataURL(file);
},false);
//data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,
js中btoa能夠把字符串轉成base64編碼。能夠經由過程這個要領舉行天生要導出的excel base64
btoa(unescape(encodeURIComponent('<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"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>' + str + '</table></body></html>')))
經由過程標籤a能夠下載一個文件:
var a = document.createElement('a');
a.href = template;
//部份網友復興說導出的excel翻開時有提醒,這是由於這裏的後綴名,帶x的時擴展名。老版本的用xls應當就能夠 了。
//a.download = 'test.xlsx';
a.download = 'test.xls';
經由過程模仿點擊事宜,觸發下載操縱
var evt = document.createEvent("MouseEvents");
evt.initEvent("click", false, false);
a.dispatchEvent(evt);
終究代碼:
function html2excel(table,name) {
// var table= '<thead><tr><th>test</th></tr></thead><tbody><tr><td>test</td></tr></tbody>';
var template = 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,' + btoa(unescape(encodeURIComponent('<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"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>' + table + '</table></body></html>')));
var a = document.createElement('a');
a.href = template;
a.download = name+'.xlsx';
var evt = document.createEvent("MouseEvents");
evt.initEvent("click", false, false);
a.dispatchEvent(evt);
}