我已经和Datatables合作了几天,我遇到了这个问题: 我有一个方法从csv文件中的Datatable下载数据,这个表有三列(Id,Type和Quantity):
_mVM.downloadCSV = function (item, event) {
var table = $("#Table" + item.Id()).DataTable();
var contentParts = [], rowParts = [], visibleColumns = [], column, data, field;
var rows = table.rows({ filter: "applied" });
var rowsData = rows.data();
var columns = table.columns();
var columnsCount = columns.data().length;
//Columns and headers
for (var i = 0; i < columnsCount; i++) {
column = table.column(i);
if (column.visible()) {
visibleColumns.push(column.dataSrc());
rowParts.push($(column.header()).html());
}
}
if (rowParts.length > 0) {
contentParts.push(rowParts.join(","));
}
// Rows
for (var rowNum = 0; rowNum < rowsData.length; rowNum++) {
rowParts = [];
for (var j = 0; j < visibleColumns.length; j++) {
field = visibleColumns[j];
data = rowsData[rowNum][field];
rowParts.push($(data).html());
}
contentParts.push(rowParts.join(","));
}
var test = contentParts.join("\n");
var dltrData = test;
var blob = new Blob([dltrData], { type: "text/csv;charset=utf-8;" });
saveAs(blob, item.selsite() + ".csv");
}
问题是在要下载的文件中我需要添加(手动)另一列,一个带有标题的空列&#39; Extra&#39;,来自数据表的那一列(那将是第四个)。是否可以使用相同的方法(downloadCSV)添加,或者只有Datatable列可以进入该文件?
答案 0 :(得分:1)
An approach roughly like this might work, where extraHeader is the name of the column, and extraRowData is an array of the values of the column in the order of the rows. You'd want to make this code more robust.
_mVM.downloadCSV = function (item, event, extraHeader, extraRowData) {
var table = $("#Table" + item.Id()).DataTable();
var contentParts = [], rowParts = [], visibleColumns = [], column, data, field;
var rows = table.rows({ filter: "applied" });
var rowsData = rows.data();
var columns = table.columns();
var columnsCount = columns.data().length;
//Columns and headers
for (var i = 0; i < columnsCount; i++) {
column = table.column(i);
if (column.visible()) {
visibleColumns.push(column.dataSrc());
rowParts.push($(column.header()).html());
}
}
if (extraHeader) rowParts.push(extraHeader);
if (rowParts.length > 0) {
contentParts.push(rowParts.join(","));
}
// Rows
for (var rowNum = 0; rowNum < rowsData.length; rowNum++) {
rowParts = [];
for (var j = 0; j < visibleColumns.length; j++) {
field = visibleColumns[j];
data = rowsData[rowNum][field];
rowParts.push($(data).html());
if(extraRowData && rowNum < extraRowData.length) rowParts.push(extraRowData[rowNum]);
}
contentParts.push(rowParts.join(","));
}
var test = contentParts.join("\n");
var dltrData = test;
var blob = new Blob([dltrData], { type: "text/csv;charset=utf-8;" });
saveAs(blob, item.selsite() + ".csv");
}