Anchor tag download attribute not working :Bug in Chrome 35.0.1916.114

后端 未结 6 1181
一整个雨季
一整个雨季 2020-11-29 04:21

I am trying to refer to this code where a we are downloading a CSV file on click of a link.

$(document).ready(function () {

    function exportTableToCSV($         


        
6条回答
  •  生来不讨喜
    2020-11-29 05:10

    When I tried this code, I was not able to get results in IE plus this code only iterates over td, it will skip any th present in your table. I have modified the code to resolve both the issues I was facing:

    $(document).ready(function () {
        function exportTableToCSV($table, filename) {
    
                var $rows = $table.find('tr'),
                tmpColDelim = String.fromCharCode(11),
                tmpHeadDelim = String.fromCharCode(11),
                tmpRowDelim = String.fromCharCode(0),
                colDelim = '","',
                headDelim = '","',
                rowDelim = '"\r\n"',
    
                csv = '"' + $rows.map(function (i, row) {
                    var $row = $(row),
                    $cols = $row.find('td');
                    $heads = $row.find('th');
    
                    var c = $heads.map(function (k, head) {
                        var $head = $(head),
                        text = $head.text();
                        return text.replace(/"/g, '""');
                    }).get().join(tmpHeadDelim);
    
                    var d = $cols.map(function (j, col) {
                        var $col = $(col),
                        text = $col.text();
                        return text.replace(/"/g, '""');
                    }).get().join(tmpColDelim);
    
                return (c+d);
    
            }).get().join(tmpRowDelim)
                .split(tmpRowDelim).join(rowDelim)
                .split(tmpHeadDelim).join(headDelim)
                .split(tmpColDelim).join(colDelim) + '"';
    
    
            var ua = window.navigator.userAgent;
            var msie = ua.indexOf("MSIE ");
    
            // if Internet Explorer (10+)
            if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
                var blob = new Blob([decodeURIComponent(csv)], {
                        type: 'text/csv;charset=utf8'
                });
                window.navigator.msSaveBlob(blob, filename);
            }
            else {
                var link = document.createElement('a');
                var blob = new Blob([csv],{type:'text/csv;charset=utf8'});
                var url = URL.createObjectURL(blob);
                link.href = url;
                link.setAttribute('download', filename);
                document.body.appendChild(link);
                link.click();
            }
        }
    
        $("#fnExcelReport").on('click', function (event) {
            var args = [$('#tableContent'), 'Report.csv'];
            exportTableToCSV.apply(this, args);
        });
    });
    

    CodePen

提交回复
热议问题