我有html表格(表格ID =' testTable')和html中的按钮:
<button id="btnExport" onclick="javascript:xport.toCSV('testTable');">CSV</button>
和javascript代码:
toCSV: function(tableId, filename) {
var date=new Date();
this._filename = (typeof filename === 'undefined') ? tableId : filename;
// Generate our CSV string from out HTML Table
var csv = this._tableToCSV(document.getElementById(tableId));
// Create a CSV Blob
var blob = new Blob([csv], { type: "text/csv" });
// Determine which approach to take for the download
if (navigator.msSaveOrOpenBlob) {
// Works for Internet Explorer and Microsoft Edge
navigator.msSaveOrOpenBlob(blob, this._filename + ".csv");
} else {
this._downloadAnchor(URL.createObjectURL(blob), 'csv');
}
}
_tableToCSV: function(table) {
// We'll be co-opting `slice` to create arrays
var slice = Array.prototype.slice;
return slice
.call(table.rows)
.map(function(row) {
return slice
.call(row.cells)
.map(function(cell) {
return '"t"'.replace("t", cell.textContent);
})
.join(",");
})
.join("\r\n");
}
我想将文件名更改为当前日期,我该怎么做?
答案 0 :(得分:1)
首先将toCSV
更改为:
toCSV: function(tableId, filename) {
var date = new Date();
this._filename = (typeof filename === 'undefined') ? date : filename;
// Generate our CSV string from out HTML Table
var csv = this._tableToCSV(document.getElementById(tableId));
// Create a CSV Blob
var blob = new Blob([csv], { type: "text/csv" });
// Determine which approach to take for the download
if (navigator.msSaveOrOpenBlob) {
// Works for Internet Explorer and Microsoft Edge
navigator.msSaveOrOpenBlob(blob, this._filename + ".csv");
} else {
this._downloadAnchor(URL.createObjectURL(blob), 'csv',this._filename);
}
}
第二次将_downloadAnchor
更改为:
_downloadAnchor: function(content, ext, filename) {
var anchor = document.createElement("a");
anchor.style = "display:none !important";
anchor.id = "downloadanchor";
document.body.appendChild(anchor);
// If the [download] attribute is supported, try to use it
if ("download" in anchor) {
anchor.download = filename + "." + ext;
}
anchor.href = content;
anchor.click();
anchor.remove();
}
答案 1 :(得分:0)
_downloadAnchor: function(content, ext) {
var anchor = document.createElement("a");
anchor.style = "display:none !important";
anchor.id = "downloadanchor";
document.body.appendChild(anchor);
// If the [download] attribute is supported, try to use it
if ("download" in anchor) {
anchor.download = this._filename + "." + ext;
}
anchor.href = content;
anchor.click();
anchor.remove();
}