您的位置:首页 > Web前端 > JQuery

JavaScript将页面表格数据导出为Excel、CSV格式文件(结合JQuery EasyUI的grid )

2017-09-06 20:42 946 查看
[align=center]JavaScript实现JQuery EasyUI的grid数据导出excel摸索纠结一下午了。[/align]
[align=center]
[/align]
 1、IE浏览器实现 ,感觉很鸡肋,不兼容  ,需要设置太多浏览器ActiveX 配置环境麻烦。
关键字:     var oXL = new ActiveXObject("Excel.Application");
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>IE导出CSV</title>
<script>
window.onload = function(){
    function exportCsv(){
        //创建AX对象excel
        var oXL = new ActiveXObject("Excel.Application");
        //获取workbook对象
        var oWB = oXL.Workbooks.Add();
        //激活当前sheet
        var oSheet = oWB.ActiveSheet;
        var Lenr = [["标题一","标题二","标题三"],["4","5","6"],["1","2","3"]];
        for (i = 0; i < Lenr.length; i++) {
            for (j = 0; j < Lenr[i].length; j++) {
                oSheet.Cells(i + 1, j + 1).value = Lenr[i][j];
            }
        }
        //设置excel可见属性
        oXL.Visible = true;
    }
    document.getElementById("J_export").onclick = function(){
        exportCsv();     
    }
}
</script>
</head>
<body>
   <a href="javascript:;" id="J_export">导出</a>
</body>
</html>




2、浏览器完全不兼容谷歌、火狐、遨游,蛋蛋的edge都不支持。

                         Uncaught ReferenceError: ActiveXObject is not defined

3、借助百度神奇的力量,找到实现的核心代码。完美实现了,,谷歌,火狐,360,IE,遨游等浏览器。

           
   function Prints() {
            //获取grid 数据
            var data = JSON.stringify($('#datagrid').datagrid('getData').rows);
            //alert(data);
            if (data == '')
                return;
            outCsv(data, "请假汇总", true);
        }
        function outCsv(JSONData, ReportTitle, ShowLabel) {
            var CSV = '';
            /*               Set Report title in first row or line  在第一集的行或行报告title */
            CSV += ReportTitle + '\r\n\n';
            /*              If JSONData is not an object then JSON.parse will parse the JSON string in an Object
                            如果JSONData不是一个对象然后JSON.parse将解析对象中的JSON字符串  */
            var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
            /*              This condition will generate the Label/Header
                            这将产生的header label
            */
            if (ShowLabel) {
                var row = "";
                /*         This loop will extract the label from 1st index of on array
                           这个循环将从数组的第一个索引中提取标签。 */
                for (var index in arrData[0]) {
                    /*              Now convert each value to string and comma-seprated
                                    现在将每个值的字符串,用逗号分开   根据实际情况重新赋值 */
                    if (index == "MM") {
                        index = "统计月份";
                    }
                    if (index == "TOTAL") {
                        index = "请假次数";
                    }
                    row += index + ',';
                }
                //截取对象内的数据。
                row = row.slice(0, -1);
                /*  append Label row with line breakappend Label row with line break
                    附加带换行符的标签行  */
                CSV += row + '\r\n';
            }
            //1st loop is to extract each row   开始遍历取数据
            for (var i = 0; i < arrData.length; i++) {
                var row = "";
                /*              2nd loop will extract each column and convert it in string comma-seprated
                                第二环路将提取每一列并将其转换成字符串逗号分开 */
                for (var index in arrData[i]) {
                    row += '"' + arrData[i][index] + '",';
                }
                row.slice(0, row.length - 1);
                //add a line break after each row
                CSV += row + '\r\n';
            }
            if (CSV == '') {
                alert("Invalid data");
                return;
            }
            //              Generate a file name    定义一个文件名一个文件名
            var fileName = "";
            //this will remove the blank-spaces from the title and replace it with an underscore
            fileName += ReportTitle.replace(/ /g, "_");
            // if browser is IE
            if (window.navigator.msSaveOrOpenBlob) {
                var csvContent = "\ufeff";
                var uriie = csvContent + CSV;
                var blob = new Blob([decodeURIComponent(encodeURI(uriie))], {
                    type: "data:text/csv;charset=utf-8,"
                });
                navigator.msSaveBlob(blob, fileName + '.csv');
            } else {
                var csvContent = "data:text/csv;charset=utf-8,\ufeff";
                var uriother = csvContent + CSV;
                // 第一种实现
                var encodedUri = encodeURI(uriother);
                var link = document.createElement("a");
                link.setAttribute("href", encodedUri);
       
4000
         link.setAttribute("download", fileName + ".csv");
                document.body.appendChild(link);
                link.click();
                //var uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURI(CSV);
                ////            Now the little tricky part.
                ////            you can use either>> window.open(uri);
                ////            but this will not work in some browsers
                ////            or you will not get the correct file extension
                ////           this trick will generate a temp <a /> tag   此技巧将生成一个临时标记
                //var link = document.createElement("a");
                //link.href = uri;
                ////                set the visibility hidden so it will not effect on your web-layout
                ////              设置可见性,这样它不会影响你的网页布局。
                //link.style = "visibility:hidden";
                //link.download = fileName + ".csv";
                ////              this part will append the anchor tag and remove it after automatic click
                ////              此部分将追加锚标记并在自动单击后删除它。
                //document.body.appendChild(link);
                //link.click();
                //document.body.removeChild(link);
            }
        }




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐