• 欢迎访问IT乐园(o゚▽゚)o
  • 推荐使用最新版火狐浏览器和Chrome浏览器访问本网站。

js导出excel

js fhy 8年前 (2017-03-16) 5885次浏览 0个评论

参考网上代码

<div id="kaoqin" style="margin: 15px;"><form id="uploadForm" action="" enctype="multipart/form-data">
<table class="listing">
<tbody>
<tr>
<th>请选择原始数据</th>
<td><input id="file" name="file" type="file" /></td>
<td><button id="upload" type="button">预览</button></td>
<td><button id="export" type="button">导出</button></td>
</tr>
</tbody>
</table>
</form>
<table id="tableExcel" border="1" width="90%" cellspacing="0" cellpadding="0"></table>
</div>
<script>
        var lock = true;
        $("#upload").on('click', function(){
            if(!lock){alert('请勿重复提交!'); return false;}
            if(!confirm("是否确认转换?")){return false;}        
            $.ajax({
                url: '/index/ajax_input_out_to_set',
                type: 'POST',
                cache: false,
                data: new FormData($('#uploadForm')[0]),
                processData: false,
                contentType: false,
                beforeSend:function(){      
                    lock = false;       
                    $("#tableExcel").html('加载中...');
                },            
            }).done(function(res) {
                $("#tableExcel").html(res);
                if(res.indexOf("not readable") >= 0){
                    return false;
                }
            }).fail(function(res) {
                alert(res.status);
                // for (r in res){
                //     alert(r)
                // }
            });
        })

        // 导出
        $("#export").on('click', function(){
            var strr = $("#tableExcel").html();
            if(strr == ''){
                alert('请先点击预览!');
                return false;            
            }
            if(strr.indexOf("not readable") >= 0){
                alert('Excel 内容错误!');
                return false;
            }

            // 获取上传文件名
            var file = $("#file").val();
            var strFileName = getFileName(file);
            var str_arr = new Array(); //定义一数组
            str_arr = strFileName.split("."); //字符分割 
            method5(tableExcel, str_arr[0]);        
        })

        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';  
            }
            else if(explorer.indexOf(".NET") >= 0){
                return 'ie';
            }  
        }  
        function method5(tableid, filename) {  
            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, '', filename)  
            }  
        }  
        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></p>
<table border="1" cellspacing="0" cellpadding="0">{table}</table>
<p></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, filename) {  
                if (!table.nodeType) table = document.getElementById(table)  
                var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
                // 1
                // window.location.href = uri + base64(format(template, ctx))  

                // 2 动态生成 a 标签下载
                var downloadLink = document.createElement("a");
                downloadLink.href = uri + base64(format(template, ctx));            
                var myDate = new Date();
                var str1 = filename.split("_")[0].replace(/^[A-Z]{2}/, ''),
                    str2 = myDate.getFullYear(),
                    str3 = parseInt(filename.split("_")[1]);
                // downloadLink.download = "000_2016_5_ 卡式报表.xls";
                downloadLink.download = str1+"_"+str2+"_"+str3+"_ 卡式报表"+".xls";
                document.body.appendChild(downloadLink);
                downloadLink.click();
                document.body.removeChild(downloadLink);            
            }  
        })()

        function getFileName(o){
            var pos=o.lastIndexOf("\");
            return o.substring(pos+1);  
        }

    </script>

IT 乐园 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:js 导出 excel
喜欢 (0)
关于作者:
九零后挨踢男
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址