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


    原文来自网络,http://blog.csdn.net/aa122273328/article/details/50388673

  • 相关阅读:
    aspnet_Applications表结构
    SQL Server 2005下的分页SQL
    海量数据查询
    对比.NET PetShop和Duwamish来探讨Ado.NET的数据库编程模式
    style.behavior的用法
    网页制作小技巧:dl dt dd标签用法
    c#中out与ref的用法与区别
    VS2005集成VSS2005的方法
    自己动手写一个JQuery插件(第一篇)(转)
    java 实现二分查找法(转)
  • 原文地址:https://www.cnblogs.com/honey01/p/7418103.html
Copyright © 2020-2023  润新知