我试图让这个tabletocsv代码转换成墙,以便在页面加载时自动下载。我尝试过各种各样的事情,包括在页面准备就绪时自动单击按钮的单独功能。什么都没有,有什么想法吗?
$(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(/"/g, '""'); // escape double quotes
}).get().join(tmpColDelim);
}).get().join(tmpRowDelim)
.split(tmpRowDelim).join(rowDelim)
.split(tmpColDelim).join(colDelim) + '"';
// Deliberate 'false', see comment below
if (false && window.navigator.msSaveBlob) {
var blob = new Blob([decodeURIComponent(csv)], {
type: 'text/csv;charset=utf8'
});
window.navigator.msSaveBlob(blob, filename);
} else if (window.Blob && window.URL) {
// HTML5 Blob
var blob = new Blob([csv], { type: 'text/csv;charset=utf8' });
var csvUrl = URL.createObjectURL(blob);
$(this)
.attr({
'download': filename,
'href': csvUrl
});
} else {
// Data URI
var 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
var d = new Date();
var args = [$('#output>table'), d+'heartbeat.csv'];
exportTableToCSV.apply(this, args);
// If CSV, don't do event.preventDefault() or return false
// We actually need this to be a typical hyperlink
});
})
我认为将点击功能更改为此功能可行,但它不会:
$(".export").ready(function (event) {
var d = new Date();
var args = [$('#output>table'), d+'heartbeat.csv'];
exportTableToCSV.apply(this, args);
});
HTML:
<a href="#" id="daily" class="export"><button class="download">Download Report</button></a>
我也试过使用id&#34;每天&#34;在按钮上而不是链接。
以下是jfiddle的测试链接:
答案 0 :(得分:1)
我添加了as.data.frame
,它就像一个魅力。
$(".download").trigger("click");