M 试图从上传的 csv 文件中创建数据表。我面临的唯一问题是定义表列标题。目前我已经这样做了,手动定义标题。
var table = $('#example').DataTable({
columns: [{
"title": "Number",
"data": "Number"
}, {
"title": "Category",
"data": "Category"
}, {
"title": "Assignment group",
"data": "Assignment group"
}
]
});
并通过 Jquery CSV 传递 csv 数据
var f = event.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
console.log("on load function");
var result = $.csv.toArrays(e.target.result);
table.rows.add($.csv.toObjects(e.target.result)).draw();
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
这工作正常。我想直接从 csv 文件本身定义列标题。
试过了
var f = event.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
console.log("on load function");
var result = $.csv.toArrays(e.target.result); // This will give CSV rows
var csvHeader = result[0]; // This will give first CSV header
var option;
$.each( csvHeader, function( value ){
console.log(value)
// Now iterate each value to define Datatable column
option = // Define column which will create below column definition
/* columns: [{
"title": "Number",
"data": "Number"
}, {
"title": "Category",
"data": "Category"
}, {
"title": "Assignment group",
"data": "Assignment group"
}, {
"title": "Short description",
"data": "Short description"
},
{
"title": "Description",
"data": "Description"
}
]*/
});
var table = $('#example').DataTable({
//Define datatable passing column definition as option
});
table.rows.add($.csv.toObjects(e.target.result)).draw();
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
提前致谢。