js导出excel表格

来源:互联网 发布:中子星 知乎 编辑:程序博客网 时间:2024/05/21 06:17
  function exportFile() {         var data = {             'key': [             {'value': "标题1"},             {'value': "标题2"}             ],             'value': [             [             {'value': "内容11"},             {'value': "内容21"}             ],             [             {'value': "内容12"},             {'value': "内容22"}             ],             [             {'value': "内容13"},             {'value': "内容23"}             ]             ]         };         if (data == '')             return;         var url = jsonToExcel(data.value, data.key);         window.open(url);     }        function jsonToExcel(value, key) {              var value = typeof value != 'object' ? JSON.parse(value) : value;        var excel = '<table>';                 //设置表头           var row = "<tr>";           for (var i = 0, l = key.length; i < l; i++) {             row += "<td>" + key[i].value + '</td>';         }                  //换行           excel += row + "</tr>";                    //设置数据           for (var i = 0; i < value.length; i++) {             var row = "<tr>";             for (var j = 0; j < value[i].length; j++) {                 var tableValue = value[i][j].value;                 row += '<td>' + tableValue + '</td>';             }             excel += row + "</tr>";         }                excel += "</table>";                var excelFile = "<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 += '<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">';         excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel';         excelFile += '; charset=UTF-8">';         excelFile += "<head>";         excelFile += "<!--[if gte mso 9]>";         excelFile += "<xml>";         excelFile += "<x:ExcelWorkbook>";         excelFile += "<x:ExcelWorksheets>";         excelFile += "<x:ExcelWorksheet>";         excelFile += "<x:Name>";         excelFile += "{worksheet}";         excelFile += "</x:Name>";         excelFile += "<x:WorksheetOptions>";         excelFile += "<x:DisplayGridlines/>";         excelFile += "</x:WorksheetOptions>";         excelFile += "</x:ExcelWorksheet>";         excelFile += "</x:ExcelWorksheets>";         excelFile += "</x:ExcelWorkbook>";         excelFile += "</xml>";         excelFile += "<![endif]-->";         excelFile += "</head>";         excelFile += "<body>";         excelFile += excel;         excelFile += "</body>";         excelFile += "</html>";                var url = 'data:application/vnd.ms-excel;charset=utf-8,' + encodeURIComponent(excelFile);         return url;     }  


 
原创粉丝点击