js 导出excel elsx格式

2018-11-21 01:34:16javascriptjs

思路,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);
    }

热门评论:


  • 涵哥 涵哥 2018-7-10 4:29 回复:

    兄弟 你这个会不会报警告扩展名不一致啊 我的也是这个方法 会报扩展名不一致 请问怎么解决啊

    • jsoncode jsoncode 2018-7-14 10:58 回复:涵哥
      不会啊,你贴一下你代码我看看

    • 2FPS 2FPS 2018-11-21 9:58 回复:涵哥

      我这打开也是这种提示,最后你是咋解决的?

    • jsoncode jsoncode 2018-11-21 1:34 回复:涵哥
      这里是因为test.xlsx后缀的问题,部分版本的office不兼容,可以把导出的文件名改成test.xls就行了


  • wang wang 2019-7-16 1:55 回复:

    改成 test.xls 也会提示的,你用office 打开试下

    • jsoncode jsoncode 2019-7-19 4:18 回复:wang
      会有问题,兼容性而已,这个方法只能导出标准格式,有些软件打不开