html页面表格导出到excel总结

最近一个项目需要把报表的表格导入excel,在网上找了一些方法,比较研究了一下,记在这里,备忘。

表格例子如下:

<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>

1、js的方法

A、将整个表格拷贝到EXCEL中

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;

}


B、读取表格中每个单元到EXCEL中:

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;
}

c、把表格输出到另一个页面,然后存成cvs格式

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 += "\r\n";
        }
    }

    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();

}

总结:比较上面3种方法,感觉第一种方法比较完美一些,因为这种方法比较完整的输出表格的格式。但,第一和第二种方法都用了ActiveX 对象,对客户端的安全有要求,而且最大的问题还有一个,就是excel 对象无法关闭。第3中方法虽然没有用ActiveX 对象,但是用了弹出窗口输出, 如果禁止了弹出窗口则无法使用。

对于execl 对象无法关闭的问题,下面的方法是一个权宜方法:

function Cleanup() {
    window.clearInterval(idTmr);
    CollectGarbage();
  }


调用方法:

idTmr = window.setInterval("Cleanup();",1);


2、Asp.net(c#)中的方法


这种方法其实类似上面的js的第3中方法(也可以在其他的web脚本来实现,比如asp中vbscript,或者php),把表格用文件流的方式


输出为excel。实例代码如下:


public void OutPutExcel(string title)
    {

        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "utf-8";

        Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(title + ".xls"));
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");

        Response.ContentType = "application/ms-excel";
        Page.EnableViewState = false;

        System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

        this.Page.RenderControl(oHtmlTextWriter);

        string temp = oStringWriter.ToString();

        Response.Write(temp);
        Response.End();
    }


这种方法的从本质上说并非标准的excel格式,不过把html格式的文件另存为excel的格式,然后用excel打开罢了。


3、利用ExceL Application或者MSOWC 或者ado.net


这种方法都是利用服务器的组件来时实现,要求服务端要安装excel,具体的代码可以看下面的链接:


http://www.cnblogs.com/pucumt/archive/2006/09/13/503120.html


http://support.microsoft.com/default.aspx?scid=kb;zh-cn;306023#top


我不提倡用这种方法,因为需要占用服务器的资源。


本文首发地址:http://www.watch-life.net/programming-notes/html-table-2-excel.html
更多文章见:守望轩[http://www.watch-life.net]



posted on 2008-06-23 22:39  xjb  阅读(2244)  评论(1编辑  收藏  举报

导航