1. 程式人生 > >HTML用JS匯出Excel的五種方法

HTML用JS匯出Excel的五種方法

這五種方法前四種方法只支援IE瀏覽器,最後一個方法支援當前主流的瀏覽器(火狐,IE,ChromeOpera,Safari

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head lang="en">  
  4.     <meta charset="UTF-8">  
  5.     <title>html 表格匯出道</title>  
  6.     <script language="JavaScript" type="text/javascript">  
  7.         //第一種方法  
  8.         function method1(tableid) {  
  9.             var curTbl = document.getElementById(tableid);  
  10.             var oXL = new ActiveXObject("Excel.Application");  
  11.             var oWB = oXL.Workbooks.Add();  
  12.             var oSheet = oWB.ActiveSheet;  
  13.             var sel = document.body.createTextRange();  
  14.             sel.moveToElementText(curTbl);  
  15.             sel.select();  
  16.             sel.execCommand("Copy");  
  17.             oSheet.Paste();  
  18.             oXL.Visible = true;  
  19.         }  
  20.         //第二種方法  
  21.         function method2(tableid)  
  22.         {  
  23.             var curTbl = document.getElementById(tableid);  
  24.             var oXL
     = new ActiveXObject("Excel.Application");  
  25.             var oWB = oXL.Workbooks.Add();  
  26.             var oSheet = oWB.ActiveSheet;  
  27.             var Lenr = curTbl.rows.length;  
  28.             for (i = 0; i < Lenr; i++)  
  29.             {        var Lenc = curTbl.rows(i).cells.length;  
  30.                 for (j = 0; j < Lenc; j++)  
  31.                 {  
  32.                     oSheet.Cells(i + 1, j + 1).value = curTbl.rows(i).cells(j).innerText;  
  33.                 }  
  34.             }  
  35.             oXL.Visible = true;  
  36.         }  
  37.         //第三種方法  
  38.         function getXlsFromTbl(inTblId, inWindow){  
  39.             try {  
  40.                 var allStr = "";  
  41.                 var curStr = "";  
  42.                 if (inTblId != null && inTblId != "" && inTblId != "null") {  
  43.                     curStr = getTblData(inTblId, inWindow);  
  44.                 }  
  45.                 if (curStr != null) {  
  46.                     allStr += curStr;  
  47.                 }  
  48.                 else {  
  49.                     alert("你要匯出的表不存在");  
  50.                     return;  
  51.                 }  
  52.                 var fileName = getExcelFileName();  
  53.                 doFileExport(fileName, allStr);  
  54.             }  
  55.             catch(e) {  
  56.                 alert("匯出發生異常:" + e.name + "->" + e.description + "!");  
  57.             }  
  58.         }  
  59.         function getTblData(inTbl, inWindow) {  
  60.             var rows = 0;  
  61.             var tblDocument = document;  
  62.             if (!!inWindow && inWindow != "") {  
  63.                 if (!document.all(inWindow)) {  
  64.                     return null;  
  65.                 }  
  66.                 else {  
  67.                     tblDocument = eval(inWindow).document;  
  68.                 }  
  69.             }  
  70.             var curTbl = tblDocument.getElementById(inTbl);  
  71.             var outStr = "";  
  72.             if (curTbl != null) {  
  73.                 for (var j = 0; j < curTbl.rows.length; j++) {  
  74.                     for (var i = 0; i < curTbl.rows[j].cells.length; i++) {  
  75.                         if (i == 0 && rows > 0) {  
  76.                             outStr += " t";  
  77.                             rows -1;  
  78.                         }  
  79.                         outStr += curTbl.rows[j].cells[i].innerText + "t";  
  80.                         if (curTbl.rows[j].cells[i].colSpan > 1) {  
  81.                             for (var k = 0; k < curTbl.rows[j].cells[i].colSpan - 1; k++) {  
  82.                                 outStr += " t";  
  83.                             }  
  84.                         }  
  85.                         if (i == 0) {  
  86.                             if (rows == 0 && curTbl.rows[j].cells[i].rowSpan > 1) {  
  87.                                 rows = curTbl.rows[j].cells[i].rowSpan - 1;  
  88.                             }  
  89.                         }  
  90.                     }  
  91.                     outStr += "rn";  
  92.                 }  
  93.             }  
  94.             else {  
  95.                 outStr = null;  
  96.                 alert(inTbl + "不存在 !");  
  97.             }  
  98.             return outStr;  
  99.         }  
  100.         function getExcelFileName() {  
  101.             var d = new Date();  
  102.             var curYear = d.getYear();  
  103.             var curMonth = "" + (d.getMonth() + 1);  
  104.             var curDate = "" + d.getDate();  
  105.             var curHour = "" + d.getHours();  
  106.             var curMinute = "" + d.getMinutes();  
  107.             var curSecond = "" + d.getSeconds();  
  108.             if (curMonth.length == 1) {  
  109.                 curMonth = "0" + curMonth;  
  110.             }  
  111.             if (curDate.length == 1) {  
  112.                 curDate = "0" + curDate;  
  113.             }  
  114.             if (curHour.length == 1) {  
  115.                 curHour = "0" + curHour;  
  116.             }  
  117.             if (curMinute.length == 1) {  
  118.                 curMinute = "0" + curMinute;  
  119.             }  
  120.             if (curSecond.length == 1) {  
  121.                 curSecond = "0" + curSecond;  
  122.             }  
  123.             var fileName = "table" + "_" + curYear + curMonth + curDate + "_"  
  124.                     + curHour + curMinute + curSecond + ".csv";  
  125.             return fileName;  
  126.         }  
  127.         function doFileExport(inName, inStr) {  
  128.             var xlsWin = null;  
  129.             if (!!document.all("glbHideFrm")) {  
  130.                 xlsWin = glbHideFrm;  
  131.             }  
  132.             else {  
  133.                 var width = 6;  
  134.                 var height = 4;  
  135.                 var openPara = "left=" + (window.screen.width / 2 - width / 2)  
  136.                         + ",top=" + (window.screen.height / 2 - height / 2)  
  137.                         + ",scrollbars=no,width=" + width + ",height=" + height;  
  138.                 xlsWin = window.open("", "_blank", openPara);  
  139.             }  
  140.             xlsWin.document.write(inStr);  
  141.             xlsWin.document.close();  
  142.             xlsWin.document.execCommand('Saveas', true, inName);  
  143.             xlsWin.close();  
  144.         }  
  145.         //第四種  
  146.         function method4(tableid){  
  147.             var curTbl = document.getElementById(tableid);  
  148.             var oXL;  
  149.             try{  
  150.                 oXL = new ActiveXObject("Excel.Application"); //建立AX物件excel  
  151.             }catch(e){  
  152.                 alert("無法啟動Excel!\n\n如果您確信您的電腦中已經安裝了Excel,"+"那麼請調整IE的安全級別。\n\n具體操作:\n\n"+"工具 → Internet選項 → 安全 → 自定義級別 → 對沒有標記為安全的ActiveX進行初始化和指令碼執行 → 啟用");  
  153.                 return false;  
  154.             }  
  155.             var oWB = oXL.Workbooks.Add(); //獲取workbook物件  
  156.             var oSheet = oWB.ActiveSheet;//啟用當前sheet  
  157.             var sel = document.body.createTextRange();  
  158.             sel.moveToElementText(curTbl); //把表格中的內容移到TextRange中  
  159.             sel.select(); //全選TextRange中內容  
  160.             sel.execCommand("Copy");//複製TextRange中內容  
  161.             oSheet.Paste();//貼上到活動的EXCEL中  
  162.             oXL.Visible = true; //設定excel可見屬性  
  163.             var fname = oXL.Application.GetSaveAsFilename("將table匯出到excel.xls", "Excel Spreadsheets (*.xls), *.xls");  
  164.             oWB.SaveAs(fname);  
  165.             oWB.Close();  
  166.             oXL.Quit();  
  167.         }  
  168.         //第五種方法  
  169.         var idTmr;  
  170.         function  getExplorer() {  
  171.             var explorer = window.navigator.userAgent ;  
  172.             //ie  
  173.             if (explorer.indexOf("MSIE") >= 0) {  
  174.                 return 'ie';  
  175.             }  
  176.             //firefox  
  177.             else if (explorer.indexOf("Firefox") >= 0) {  
  178.                 return 'Firefox';  
  179.             }  
  180.             //Chrome  
  181.             else if(explorer.indexOf("Chrome") >= 0){  
  182.                 return 'Chrome';  
  183.             }  
  184.             //Opera  
  185.             else if(explorer.indexOf("Opera") >= 0){  
  186.                 return 'Opera';  
  187.             }  
  188.             //Safari  
  189.             else if(explorer.indexOf("Safari") >= 0){  
  190.                 return 'Safari';  
  191.             }  
  192.         }  
  193.         function method5(tableid) {  
  194.             if(getExplorer()=='ie')  
  195.             {  
  196.                 var curTbl = document.getElementById(tableid);  
  197.                 var oXL = new ActiveXObject("Excel.Application");  
  198.                 var oWB = oXL.Workbooks.Add();  
  199.                 var xlsheet = oWB.Worksheets(1);  
  200.                 var sel = document.body.createTextRange();  
  201.                 sel.moveToElementText(curTbl);  
  202.                 sel.select();  
  203.                 sel.execCommand("Copy");  
  204.                 xlsheet.Paste();  
  205.                 oXL.Visible = true;  
  206.                 try {  
  207.                     var fname = oXL.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls");  
  208.                 } catch (e) {  
  209.                     print("Nested catch caught " + e);  
  210.                 } finally {  
  211.                     oWB.SaveAs(fname);  
  212.                     oWB.Close(savechanges = false);  
  213.                     oXL.Quit();  
  214.                     oXL = null;  
  215.                     idTmr = window.setInterval("Cleanup();", 1);  
  216.                 }  
  217.             }  
  218.             else  
  219.             {  
  220.                 tableToExcel(tableid)  
  221.             }  
  222.         }  
  223.         function Cleanup() {  
  224.             window.clearInterval(idTmr);  
  225.             CollectGarbage();  
  226.         }  
  227.         var tableToExcel = (function() {  
  228.             var uri = 'data:application/vnd.ms-excel;base64,',  
  229.                     template = '<html><head><meta charset="UTF-8"></head><body><table>{table}</table></body></html>',  
  230.                     base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) },  
  231.                     format = function(s, c) {  
  232.                         return s.replace(/{(\w+)}/g,  
  233.                                 function(m, p) { return c[p]; }) }  
  234.             return function(table, name) {  
  235.                 if (!table.nodeType) table = document.getElementById(table)  
  236.                 var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}  
  237.                 window.location.href = uri + base64(format(template, ctx))  
  238.             }  
  239.         })()  
  240.     </script>  
  241. </head>  
  242. <body>  
  243. <div >  
  244.     <button type="button" onclick="method1('tableExcel')">匯出Excel方法一</button>  
  245.     <button type="button" onclick="method2('tableExcel')">匯出Excel方法二</button>  
  246.     <button type="button" onclick="getXlsFromTbl('tableExcel','myDiv')">匯出Excel方法三</button>  
  247.     <button type="button" onclick="method4('tableExcel')">匯出Excel方法四</button>  
  248.     <button type="button" onclick="method5('tableExcel')">匯出Excel方法五</button>  
  249. </div>  
  250. <div id="myDiv">  
  251. <table id="tableExcel" width="100%" border="1" cellspacing="0" cellpadding="0">  
  252.     <tr>  
  253.         <td colspan="5" align="center">html 表格匯出道Excel</td>  
  254.     </tr>  
  255.     <tr>  
  256.         <td>列標題1</td>  
  257.         <td>列標題2</td>  
  258.         <td>類標題3</td>  
  259.         <td>列標題4</td>  
  260.         <td>列標題5</td>  
  261.     </tr>  
  262.     <tr>  
  263.         <td>aaa</td>  
  264.         <td>bbb</td>  
  265.         <td>ccc</td>  
  266.         <td>ddd</td>  
  267.         <td>eee</td>  
  268.     </tr>  
  269.     <tr>  
  270.         <td>AAA</td>  
  271.         <td>BBB</td>  
  272.         <td>CCC</td>  
  273.         <td>DDD</td>  
  274.         <td>EEE</td>  
  275.     </tr>  
  276.     <tr>  
  277.         <td>FFF</td>  
  278.         <td>GGG</td>  
  279.         <td>HHH</td>  
  280.         <td>III</td>  
  281.         <td>JJJ</td>  
  282.     </tr>  
  283. </table>  
  284. </div>  
  285. </body>  
  286. </html>