Javascript导出Excel的方法

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://linuxstyle.blog.csdn.net/article/details/7096052
 
<SCRIPT LANGUAGE="javascript"> 
 function method1(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 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> 


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

<table id="tableExcel" width="100%" border="1" cellspacing="0" cellpadding="0"> 
<tr>.....

说明第二种方法最好


展开阅读全文

[讨论]javascript导出excel

08-28

下面是在网上找的一段js导excel代码,我做了一些改动。rn function htmlToExcel(elTableOut,elDiv) rn try rn //设置导出前的数据,为导出后返回格式而设置 rn var elDivStrBak = elDiv.innerHTML; rn //设置table的border=1,这样到excel中就有表格线rn elTableOut.border=1; rn //过滤elDiv内容 rn var elDivStr = elDiv.innerHTML; rn elDivStr = replaceHtml(elDivStr,""); rn elDivStr = replaceHtml(elDivStr,""); rn elDiv.innerHTML=elDivStr;rn var oRangeRef = document.body.createTextRange(); rn oRangeRef.moveToElementText( elDiv ); rn oRangeRef.execCommand("Copy"); //复制内容到剪切板rn rn //返回格式变换以前的内容 rn elDiv.innerHTML = elDivStrBak; rn //内容数据可能很大,所以赋空 rn elDivStrBak = ""; rn elDivStr = ""; rn try rn var oXL = new ActiveXObject("Excel.Application") rn rn catch(e) rn alert( "需要安装Excel电子表格软件,同时浏览器须使用“ActiveX 控件”,您的浏览器须允许执行控件。");rn return "";rn rn var oWB = oXL.Workbooks.Add ; rn var oSheet = oWB.ActiveSheet ; rn oSheet.Paste(); rn// oSheet.Cells.NumberFormatLocal = "@";#,##0.00rn oSheet.Columns("A:A").ColumnWidth=35;rn oSheet.Columns("B:B").ColumnWidth=10;rn oSheet.Columns("C:C").ColumnWidth=35;rn oSheet.Columns("D:D").ColumnWidth=10;rn oSheet.Columns(1).NumberFormatLocal="@";rn oSheet.Columns(3).NumberFormatLocal="@";rn oSheet.Columns(2).NumberFormatLocal="0.00";//设置格式rn oSheet.Columns(4).NumberFormatLocal="0.00";rn// oXL.Visible = true;rn// oXL.UserControl = true;rn var fileName;rn// dorn fileName = oXL.Application.GetSaveAsFilename("save.xls", "Excel Spreadsheets (*.xls), *.xls");rn// while(fileName==null||fileName=="")rn oWB.SaveAs(fileName);rn rn oXL.DisplayAlerts = "False";rn oXL.Quit();rn oXL = null;rn oSheet = null; rn oWB = null;rn idTmr = window.setInterval("Cleanup();",1000); //回收内存rn catch(e)rn oXL = null;rn oSheet = null; rn oWB = null;rn alert(e.description)rn oXL.DisplayAlerts = "False";rn oXL.Quit();rn CollectGarbage();rn rnrnfunction Cleanup() rnwindow.clearInterval(idTmr); rnCollectGarbage(); rnrnfunction replaceHtml(replacedStr,repStr,endStr) rn var replacedStrF = ""; rn var replacedStrB = ""; rn var repStrIndex = replacedStr.indexOf(repStr); rn while(repStrIndex != -1) rn replacedStrF = replacedStr.substring(0,repStrIndex); rn replacedStrB = replacedStr.substring(repStrIndex,replacedStr.length); rn replacedStrB = replacedStrB.substring(replacedStrB.indexOf(endStr)+1,replacedStrB.length); rn replacedStr = replacedStrF + replacedStrB; rn repStrIndex = replacedStr.indexOf(repStr); rn rn return replacedStr; rnrn在js里用oXL.Application.GetSaveAsFilename("save.xls", "Excel Spreadsheets (*.xls), *.xls");rn确实可以调出excel的保存文件对话框,但是这个对话框不是活动的,必须是“显示桌面”,再打开改IE页面,才能看到这个保存对话框。不知道有没有办法让它直接得到焦点。excel进程可以退出,CollectGarbage()回收js内存。rn可以直接用SaveAs()方法用固定文件名固定路径保存。只是用户体验不好。欢迎大家讨论。 论坛

JavaScript EXCEl 导出问题

08-20

我使用别人的方法实现excel 导出问题,但是点击导出的时候出现两个弹框,一个是数据内容弹框,一个是excel存储选择的弹框,请教大神,如何把数据内容的弹框隐藏掉,rn问题图片rn[img=https://img-bbs.csdn.net/upload/201708/20/1503240380_187194.png][/img]rn相关的js代码:rn[code=javascript]rn function Save_Excel(e, c) //导出Excel文件rn var data = $(e).datagrid('getExcelXml', title: 'datagrid import to excel', hidde: c,hidden:true ); var curr_time = new Date();rn var strDate = curr_time.getFullYear() + "-";rn strDate += curr_time.getMonth() + 1 + "-";rn strDate += curr_time.getDate() + "-";rn strDate += curr_time.getHours() + "-";rn strDate += curr_time.getMinutes() + "-";rn strDate += curr_time.getSeconds();rnrn//[color=#FF0000]问题主要是这个地方[/color]rn var screen = window.screen, fSaveWindow = window.open('', '_blank', 'width=' + Math.round(screen.width * 0.5) + ',height=' + Math.round(screen.height * 0.5) + ',left=' + Math.round(screen.width * 0.05));rn fSaveWindow.document.write(data);rn if ((navigator.userAgent.indexOf('MSIE') >= 0)rn && (navigator.userAgent.indexOf('Opera') < 0)rn || (!!window.ActiveXObject || "ActiveXObject" in window)rn || (navigator.userAgent.indexOf('Edge') >= 0))//包括Microsoft IE和Microsoft Edgern rn fSaveWindow.document.execCommand("SaveAs", true, strDate + ".xls");rn //Firefox浏览器的支持rn else if (navigator.userAgent.indexOf('Firefox') >= 0) rn var aLink = document.createElement('a');rn var blob = new Blob([data]);rn var evt = document.createEvent("HTMLEvents");rn evt.initEvent("click", true, true);rn aLink.download = strDate + ".xls";rn aLink.href = URL.createObjectURL(blob);rn aLink.dispatchEvent(evt);rn document.body.appendChild(aLink);rn aLink.click();rn rn //其他如Chrome和360浏览器的支持rn else rn var aLink = fSaveWindow.document.createElement('a');rn var blob = new Blob([data]);rn var evt = fSaveWindow.document.createEvent("HTMLEvents");rn evt.initEvent("click", false, false);rn aLink.download = strDate + ".xls";rn aLink.href = URL.createObjectURL(blob);rn aLink.dispatchEvent(evt);rn rnrn fSaveWindow.close();rn rnrn[/code] 论坛

没有更多推荐了,返回首页