JS 使用xlsx.core.js 数据导出到excel

/* 通用导出数据  需要引入 xlsx.core.js
    * data:数据
    * th:表头
    * filename:导出表格名称
    */
    var data = [];
    var th = [
            ["js导出excel表", "", "", "", "", ""],
            ["标题1", "标题2", "标题3", "标题4", "标题5", "标题6"],
    ];
    var filename = "导出表格名称";
  exportData(data, th, filename); function exportData(data, th, filename) { var deferred = $.Deferred(); data = data || []; th = th || []; var merges = []; merges.push({ s: { //s为开始 c: 0, //开始列 r: 0 //开始行 }, e: { //e结束 c: 5, //结束列 r: 0 //结束行 } }); if (data.length === 0 || th.length === 0) {
       console.log("缺少数据"); deferred.reject();
return; } filename = filename || '数据导出'; filename += '_' + moment(new Date()).format('YYYYMMDDHHmmss') + '.xlsx'; // moment 时间插件(如不需要,可以去掉) var loadedData = []; var i = 0; loadedData = loadedData.concat(th); for (i = 0; i < data.length; ++i) { var item = data[i]; var obj = []; obj.push(item.title1 || "-"); obj.push(item.title2 || "-"); obj.push(item.title3 || "-"); obj.push(item.title4 || "-"); obj.push(item.title5 || "-"); obj.push(item.title6 || "-"); loadedData.push(obj); } initFile(); function initFile() { var wb = XLSX.utils.book_new(), ws = XLSX.utils.aoa_to_sheet(loadedData); ws['!merges'] = merges; // 合并单元格 XLSX.utils.book_append_sheet(wb, ws, "sheet1"); XLSX.writeFile(wb, filename, { compression: true }); deferred.resolve(); } return deferred.promise(); }

 

posted @ 2020-12-01 11:20  手指键盘摩擦  阅读(1082)  评论(0编辑  收藏  举报