Javascript實現把網頁中table的內容導入到excel中的幾種方法

Javascript實現把網頁中table的內容導入到excel中的幾種方法 

1、            直接拷貝整個表格到EXCEL中 
2、            經過遍歷表格,給EXCEL中相應的單元格賦值。 
3、            把表格中的內容提取出來,利用IE的另存爲.csv的格式。 

各方法的好處: 
1.      直接拷貝表格,可以保留表格中的原有的格式,好比,列,行的合併,對齊方式,底色等等, 
2.      經過遍歷表格,比較靈活,能夠遍歷表格某些須要部分的內容。 
3.      利用IE的另存爲,不用建立ActiveXObject對象,能夠處理表格合併方面的問題。 

各方法的缺點: 
1.      可能彈出腳本錯誤:Automation不能建立對象。 
解決方法:啓用IE安全設置中的:對沒有標記爲安全的ActiveX控件進行初始化和腳本運行。 
因爲整個表格複製到EXCEL中,給表格加個標題,並加入到EXCEL中可能會遇到麻煩。 
解決方法:首先在表格中加入第一行 

<tr><td colspan="x" align="center">&</td></tr> 
X,表示整個表格的列數,複製完整個表格後,加以下代碼,oSheet爲當前活動的sheet. 
oSheet.Range(oSheet.Cells(1, 1), oSheet.Cells(1, x)).value = "表格標題";//設置標題 
oSheet.Rows(1).Font.Size = 16;   //設置文字大小           
oSheet.Rows(1).Font.Name = "宋體";//設置文字字體 
注:如下屬性我沒用着,可能有用,也可能會報錯 

oSheet.Range(oSheet.Cells(1,1), oSheet.Cells(1,14)).mergecells=true; //合併單元格 
oSheet.Range(oSheet.Cells(1,1), oSheet.Cells(1,14)).Interior.ColorIndex=6;//設置底色? 
oSheet.Range(oSheet.Cells(1,1), oSheet.Cells(1,14)).Font.ColorIndex=5;//設置字體色? 
oSheet.Rows(1).RowHeight=20; //設置列高 
oSheet.Cells(iRow,iCol).Halignment=’2’//設置字體居中 

2.      可能彈出腳本錯誤:Automation不能建立對象(解決方法如上)。 
表格內容寫入到EXCEL中無表格線(未解決) 
且有單元格合併時會有問題,解決方法:合併單元格後再寫數據。 

oSheet.Range(oSheet.Cells(1,1), oSheet.Cells(1,14)).mergecells=true; //合併單元格 


3.      表格內容寫入到EXCEL中無表格線(未解決) 

表格格式複雜時,會有問題,(rowspan>1 or colspan>1),解決方法:通常都是表頭格式比較複雜,可先把表頭寫死,而後再循環寫其餘數據。 

網頁內容以下:(可直接拷貝到記事本,而後保存爲html格式,用IE打開,有問題歡迎交流:joyleo@126.com) 
javascript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=gbk"/>
    <title>WEB頁面導出爲EXCEL文檔的方法</title>
</head>
<body>
<table id="tableExcel" width="100%" border="1" cellspacing="0" cellpadding="0">
    <tr>
        <td colspan="5" align="center">WEB頁面導出爲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>
<input type="button" onclick="javascript:method1('tableExcel');" value="第一種方法導入到EXCEL">
<input type="button" onclick="javascript:method2('tableExcel');" value="第二種方法導入到EXCEL">
<input type="button" onclick="javascript:getXlsFromTbl('tableExcel',null);" value="第三種方法導入到EXCEL">

<SCRIPT LANGUAGE="javascript">
function method1(tableid) {//整個表格拷貝到EXCEL中
    var curTbl = document.getElementById(tableid);
    var oXL = new ActiveXObject("Excel.Application");// var oXL = new ActiveXObject("ET.Application"); wps
    //建立AX對象excel
    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可見屬性
}

function method2(tableid) //讀取表格中每一個單元到EXCEL中
{
    var curTbl = document.getElementById(tableid);
    var oXL = new ActiveXObject("Excel.Application");
    //建立AX對象excel
    var oWB = oXL.Workbooks.Add();
    //獲取workbook對象
    var oSheet = oWB.ActiveSheet;
    //激活當前sheet
    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;
    //設置excel可見屬性
}

function getXlsFromTbl(inTblId, inWindow) {
    try {
        var allStr = "";
        var curStr = "";
        //alert("getXlsFromTbl");
        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;
    //alert("getTblData is " + inWindow);
    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++) {
            //alert("j is " + j);
            for (var i = 0; i < curTbl.rows[j].cells.length; i++) {
                //alert("i is " + 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 = "leo_zhang" + "_" + curYear + curMonth + curDate + "_" + curHour + curMinute + curSecond + ".csv";
    //alert(fileName);
    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();
}

</SCRIPT>
</body>
</html>
相關文章
相關標籤/搜索