将html表导出为CSV无法使用javascript工作 [英] Export html table to CSV not working using javascript

查看:76
本文介绍了将html表导出为CSV无法使用javascript工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我使用javascript代码将我的html表导出到csv,使用锚标记中的download属性。我检查了兼容性,它与我的谷歌浏览器版本兼容。但是当我将表下载到csv时,它不会向我显示表中的数据,而是显示页面的html标记和脚本。对此有何想法?我正在使用这个javascript代码



Hi,

I used a javascript code to export my html table to csv, using the download attribute in the anchor tag. I checked the compatibility and it is compatible with the version of my google chrome. But when I download the tables to csv, it does not show me the data in the table, but the html tags and scripts of the page. Any idea about this? I am using this javascript code

/**
 * ExcellentExport.
 * A client side Javascript export to Excel.
 *
 * @author: Jordi Burgos (jordiburgos@gmail.com)
 *
 * Based on:
 * https://gist.github.com/insin/1031969
 * http://jsfiddle.net/insin/cmewv/
 *
 * CSV: http://en.wikipedia.org/wiki/Comma-separated_values
 */

/*
 * Base64 encoder/decoder from: http://jsperf.com/base64-optimized
 */


var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var fromCharCode = String.fromCharCode;
var INVALID_CHARACTER_ERR = ( function() {
        // fabricate a suitable error object
        try {
            document.createElement('$');
        } catch (error) {
            return error;
        }
    }());

// encoder
window.btoa || (window.btoa = function(string) {
    var a, b, b1, b2, b3, b4, c, i = 0, len = string.length, max = Math.max, result = '';

    while (i < len) {
        a = string.charCodeAt(i++) || 0;
        b = string.charCodeAt(i++) || 0;
        c = string.charCodeAt(i++) || 0;

        if (max(a, b, c) > 0xFF) {
            throw INVALID_CHARACTER_ERR;
        }

        b1 = (a >> 2) & 0x3F;
        b2 = ((a & 0x3) << 4) | ((b >> 4) & 0xF);
        b3 = ((b & 0xF) << 2) | ((c >> 6) & 0x3);
        b4 = c & 0x3F;

        if (!b) {
            b3 = b4 = 64;
        } else if (!c) {
            b4 = 64;
        }
        result += characters.charAt(b1) + characters.charAt(b2) + characters.charAt(b3) + characters.charAt(b4);
    }
    return result;
});

// decoder
window.atob || (window.atob = function(string) {
    string = string.replace(/=+$/, '');
    var a, b, b1, b2, b3, b4, c, i = 0, len = string.length, chars = [];

    if (len % 4 === 1)
        throw INVALID_CHARACTER_ERR;

    while (i < len) {
        b1 = characters.indexOf(string.charAt(i++));
        b2 = characters.indexOf(string.charAt(i++));
        b3 = characters.indexOf(string.charAt(i++));
        b4 = characters.indexOf(string.charAt(i++));

        a = ((b1 & 0x3F) << 2) | ((b2 >> 4) & 0x3);
        b = ((b2 & 0xF) << 4) | ((b3 >> 2) & 0xF);
        c = ((b3 & 0x3) << 6) | (b4 & 0x3F);

        chars.push(fromCharCode(a));
        b && chars.push(fromCharCode(b));
        c && chars.push(fromCharCode(c));
    }
    return chars.join('');
});


ExcellentExport = (function() {
    var version = "1.3";
    var uri = {excel: 'data:application/vnd.ms-excel;base64,', csv: 'data:application/csv;base64,'};
    var template = {excel: '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'};
    var base64 = function(s) {
        return window.btoa(unescape(encodeURIComponent(s)));
    };
    var format = function(s, c) {
        return s.replace(/{(\w+)}/g, function(m, p) {
            return c[p];
        });
    };

    var get = function(element) {
        if (!element.nodeType) {
            return document.getElementById(element);
        }
        return element;
    };

    var fixCSVField = function(value) {
        var fixedValue = value;
        var addQuotes = (value.indexOf(',') !== -1) || (value.indexOf('\r') !== -1) || (value.indexOf('\n') !== -1);
        var replaceDoubleQuotes = (value.indexOf('"') !== -1);

        if (replaceDoubleQuotes) {
            fixedValue = fixedValue.replace(/"/g, '""');
        }
        if (addQuotes || replaceDoubleQuotes) {
            fixedValue = '"' + fixedValue + '"';
        }
        return fixedValue;
    };

    var tableToCSV = function(table) {
        var data = "";
        for (var i = 0, row; row = table.rows[i]; i++) {
            for (var j = 0, col; col = row.cells[j]; j++) {
                alert(data);
                data = data + (j ? ',' : '') + fixCSVField(col.innerHTML);
            }
            data = data + "\r\n";
        }
        return data;
    };

    var ee = {
        /** @expose */
        excel: function(anchor, table, name) {
            table = get(table);
            var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML};
            var hrefvalue = uri.excel + base64(format(template.excel, ctx));
            anchor.href = hrefvalue;
            // Return true to allow the link to work
            return true;
        },
        /** @expose */
       /* csv: function(anchor, table) {
            table = get(table);
            var csvData = tableToCSV(table);
            var hrefvalue = uri.csv + base64(csvData);
            //anchor.href = hrefvalue;
            return true;
        }*/
        csv: function(table) {
            table = get(table);
            var csvData = tableToCSV(table);
            var hrefvalue = uri.csv + base64(csvData);
            //anchor.href = hrefvalue;
            return true;
        }
    };

    return ee;
}());

推荐答案

');
} catch (错误){
return 错误;
}
}());

// 编码器
window.btoa || (window.btoa = function( string ){
var a,b,b1,b2 ,b3,b4,c,i = 0 ,len = string .length,max = Math.max ,result = ' ';

while (i < len){
a = string .charCodeAt (i ++)|| 0 ;
b = string .charCodeAt(i ++)|| 0 ;
c = string .charCodeAt(i ++)|| 0 ;

if (max(a,b,c)> ; 0xFF){
throw INVALID_CHARACTER_ERR;
}

b1 =(a>> 2 )& 0x3F的;
b2 =((a& 0x3)<< 4 )| ((b>> 4 )& 0xF);
b3 =((b& 0xF)<< 2 )| ((c>> 6 )& 0x3);
b4 = c& 0x3F的;

if (!b){
b3 = b4 = 64 ;
} 其他 如果(!c){
b4 = 64 ;
}
结果+ = characters.charAt(b1)+ characters.charAt(b2)+ characters.charAt(b3)+ characters.charAt(b4);
}
返回结果;
});

// decoder
window.atob || (window.atob = function( string ){
string = string .replace(/ = +
'); } catch (error) { return error; } }()); // encoder window.btoa || (window.btoa = function(string) { var a, b, b1, b2, b3, b4, c, i = 0, len = string.length, max = Math.max, result = ''; while (i < len) { a = string.charCodeAt(i++) || 0; b = string.charCodeAt(i++) || 0; c = string.charCodeAt(i++) || 0; if (max(a, b, c) > 0xFF) { throw INVALID_CHARACTER_ERR; } b1 = (a >> 2) & 0x3F; b2 = ((a & 0x3) << 4) | ((b >> 4) & 0xF); b3 = ((b & 0xF) << 2) | ((c >> 6) & 0x3); b4 = c & 0x3F; if (!b) { b3 = b4 = 64; } else if (!c) { b4 = 64; } result += characters.charAt(b1) + characters.charAt(b2) + characters.charAt(b3) + characters.charAt(b4); } return result; }); // decoder window.atob || (window.atob = function(string) { string = string.replace(/=+


/,' ');
var a,b,b1,b2,b3,b4,c,i = 0 ,len = 字符串 .length,chars = [];

if (len% 4 === 1
throw INVALID_CHARACTER_ERR;

while (i < len){
b1 = characters.indexOf( string .charAt(i ++));
b2 = characters .indexOf( string .charAt(i ++));
b3 = characters.indexOf( .charAt(I ++));
b4 = characters.indexOf( string .charAt(i ++));

a =((b1& 0x3F)<< 2 )| ((b2>> 4 )& 0x3);
b =((b2& 0xF)<< 4 )| ((b3>>> 2 )& 0xF);
c =((b3& 0x3)<< 6 )| (b4& 0x3F);

chars.push(fromCharCode(a));
b&& chars.push(fromCharCode(B));
c&& chars.push(fromCharCode(C));
}
return chars。 join ' ');
});


ExcellentExport =(function(){
var version = 1.3;
var uri = {excel: data:application / vnd.ms-excel; base64,',csv:' data:application / csv; base64,'};
var template = {excel:' < html xmlns:o =urn:schemas-microsoft-com:office:office xmlns:x =urn:schemas-microsoft-com:office:excelxmlns =http://www.w3.org/TR/REC-html40>< head>< meta http-equiv = Content-Typecontent =text / html; charset = UTF-8><! - [if gte mso 9]>< xml>< x:ExcelWorkbook>< x:ExcelWorksheets>< X:ExcelWorksheet>< X:名称> {工作表}< / X:名称>< X:WorksheetOptions>< X:显示网格线/>< / X:WorksheetOptions>< / X:ExcelWorksheet>< / X:ExcelWorksheets>< / X:ExcelWorkbook>< / XML>< ENDIF] - GT;< /头><主体><表> {表}< /表>< / BODY>< / HTML>'};
var base64 = function(s){
return window.btoa(unescape (encodeURIComponent方法(一个或多个)));
};
var format = function(s,c){
return s.replace (/ {(\w +)} / g,function(m,p){
return c [p];
});
};

var get = function(element){
if (!element.nodeType){
return document.getElementById(element);
}
return 元素;
};

var fixCSVField = function( value ){
var fixedValue = value ;
var addQuotes =( value .indexOf( ' ,')!== -1)|| ( value .indexOf(' \ r')!== -1)|| ( value .indexOf(' \ n')!== -1);
var replaceDoubleQuotes =( value .indexOf( ' ')!== -1);

if (replaceDoubleQuotes){
fixedValue = fixedValue.replace(/ / g,' ');
}
if(addQuotes || replaceDoubleQuotes){
fixedValue ='
' + fixedValue +' ';
}
返回fixedValue;
};

var tableToCSV = function(table){
var data =
;
for(var i = 0,row; row = table.rows [i]; i ++){
for(var j = 0,col; col = row.cells [j]; j ++){
alert(data);
data = data +(j?',':'')+ fixCSVField(col.innerHTML);
}
data = data +
\\\\ n ;
}
返回数据;
};

var ee = {
/ ** @expose * /
excel:function(anchor,table,name){
table = get(table);
var ctx = {工作表:名称|| '工作表',表:table.innerHTML};
var hrefvalue = uri.excel + base64(format(template.excel,ctx));
anchor.href = hrefvalue;
//返回true以允许链接工作
返回true;
},
/ ** @expose * /
/ * csv:function(anchor,table){
table = get(table);
var csvData = tableToCSV(table);
var hrefvalue = uri.csv + base64(csvData);
//anchor.href = hrefvalue;
返回true;
} * /
csv:function(table){
table = get(table);
var csvData = tableToCSV(table);
var hrefvalue = uri.csv + base64(csvData);
//anchor.href = hrefvalue;
返回true;
}
};

返回ee;
}());
/, ''); var a, b, b1, b2, b3, b4, c, i = 0, len = string.length, chars = []; if (len % 4 === 1) throw INVALID_CHARACTER_ERR; while (i < len) { b1 = characters.indexOf(string.charAt(i++)); b2 = characters.indexOf(string.charAt(i++)); b3 = characters.indexOf(string.charAt(i++)); b4 = characters.indexOf(string.charAt(i++)); a = ((b1 & 0x3F) << 2) | ((b2 >> 4) & 0x3); b = ((b2 & 0xF) << 4) | ((b3 >> 2) & 0xF); c = ((b3 & 0x3) << 6) | (b4 & 0x3F); chars.push(fromCharCode(a)); b && chars.push(fromCharCode(b)); c && chars.push(fromCharCode(c)); } return chars.join(''); }); ExcellentExport = (function() { var version = "1.3"; var uri = {excel: 'data:application/vnd.ms-excel;base64,', csv: 'data:application/csv;base64,'}; var template = {excel: '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'}; var base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))); }; var format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }); }; var get = function(element) { if (!element.nodeType) { return document.getElementById(element); } return element; }; var fixCSVField = function(value) { var fixedValue = value; var addQuotes = (value.indexOf(',') !== -1) || (value.indexOf('\r') !== -1) || (value.indexOf('\n') !== -1); var replaceDoubleQuotes = (value.indexOf('"') !== -1); if (replaceDoubleQuotes) { fixedValue = fixedValue.replace(/"/g, '""'); } if (addQuotes || replaceDoubleQuotes) { fixedValue = '"' + fixedValue + '"'; } return fixedValue; }; var tableToCSV = function(table) { var data = ""; for (var i = 0, row; row = table.rows[i]; i++) { for (var j = 0, col; col = row.cells[j]; j++) { alert(data); data = data + (j ? ',' : '') + fixCSVField(col.innerHTML); } data = data + "\r\n"; } return data; }; var ee = { /** @expose */ excel: function(anchor, table, name) { table = get(table); var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}; var hrefvalue = uri.excel + base64(format(template.excel, ctx)); anchor.href = hrefvalue; // Return true to allow the link to work return true; }, /** @expose */ /* csv: function(anchor, table) { table = get(table); var csvData = tableToCSV(table); var hrefvalue = uri.csv + base64(csvData); //anchor.href = hrefvalue; return true; }*/ csv: function(table) { table = get(table); var csvData = tableToCSV(table); var hrefvalue = uri.csv + base64(csvData); //anchor.href = hrefvalue; return true; } }; return ee; }());


请参阅此jsfiddle示例。这是有效的。



http://jsfiddle.net/KPEGU/2017 / [ ^ ]
See this jsfiddle example. This is working.

http://jsfiddle.net/KPEGU/2017/[^]


这篇关于将html表导出为CSV无法使用javascript工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆