Javascript 将HTML表格导出到CSV(任何浏览器)
我尝试了很多将HTML数据导出到CSV的解决方案,但没有一个与所有浏览器兼容 这:在Firefox、Chrome上很好用,但在IE上不起作用。有没有可能在任何浏览器上都能工作Javascript 将HTML表格导出到CSV(任何浏览器),javascript,jquery,csv,export,Javascript,Jquery,Csv,Export,我尝试了很多将HTML数据导出到CSV的解决方案,但没有一个与所有浏览器兼容 这:在Firefox、Chrome上很好用,但在IE上不起作用。有没有可能在任何浏览器上都能工作 $(document).ready(function () { function exportTableToCSV($table, filename) { var $rows = $table.find('tr:has(td)'), // Temporary delim
$(document).ready(function () {
function exportTableToCSV($table, filename) {
var $rows = $table.find('tr:has(td)'),
// Temporary delimiter characters unlikely to be typed by keyboard
// This is to avoid accidentally splitting the actual contents
tmpColDelim = String.fromCharCode(11), // vertical tab character
tmpRowDelim = String.fromCharCode(0), // null character
// actual delimiter characters for CSV format
colDelim = '";"',
rowDelim = '"\r\n"',
// Grab text from table into CSV formatted string
csv = '"' + $rows.map(function (i, row) {
var $row = $(row),
$cols = $row.find('td');
return $cols.map(function (j, col) {
var $col = $(col),
text = $col.text();
return text.replace('"', '""'); // escape double quotes
}).get().join(tmpColDelim);
}).get().join(tmpRowDelim)
.split(tmpRowDelim).join(rowDelim)
.split(tmpColDelim).join(colDelim) + '"',
// Data URI
csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
$(this)
.attr({
'download': filename,
'href': csvData,
'target': '_blank'
});
}
// This must be a hyperlink
$(".export").on('click', function (event) {
// CSV
exportTableToCSV.apply(this, [$('table#two'), 'export.csv']);
// IF CSV, don't do event.preventDefault() or return false
// We actually need this to be a typical hyperlink
});
});
有很多库或插件已经过跨浏览器测试,为什么要重新发明轮子?一个很快就浮现在脑海的是table2CSV。相信我,我尝试了很多,但都不适用于Firefox、Chrome和IE。^不适用于IE。