【问题标题】:How to Load Csv values in Datatable? [duplicate]如何在 Datatable 中加载 Csv 值? [复制]
【发布时间】:2021-09-15 18:35:37
【问题描述】:
如何从 csv 文件中读取值并使用 datatables 插件将其加载到表中?
我有一张静态表格:
<table id="myTable" class="table table-striped" >
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
<th>6</th>
<th>7</th>
<th>8</th>
<th>9</th>
</tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td>s</td>
<td>d</td>
<td>f</td>
<td>f</td>
<td>f</td>
<td>f</td>
<td>f</td>
<td>f</td>
</tr>
<tr>
<td>a</td>
<td>s</td>
<td>d</td>
<td>f</td>
<td>f</td>
<td>f</td>
<td>f</td>
<td>f</td>
<td>f</td>
</tr>
</tbody>
</table>
</div>
</body>
<script>
$(document).ready(function(){
$('#myTable').dataTable();
});
</script>
但是我不想在 html 标签中定义所有数据,而是想从 csv 文件中读取值,我该如何实现呢?
【问题讨论】:
标签:
javascript
html
jquery
datatables
【解决方案1】:
我已经编写了一段代码来完全按照您的意愿行事:
document.getElementById('yourfile').onchange = function(evt) {
var files = document.getElementById('yourfile').files; // FileList object
var csv2json = new CSVToJSON();
csv2json.parseCSV(files[0]);
}
var CSVToJSON = function() {
this.parseCSV = function(file) {
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
var json_object = _convertCSVtoJSON(data);
Json2table(json_object);
};
reader.onerror = function(ex) {
console.log(ex);
};
reader.readAsBinaryString(file);
};
};
function _convertCSVtoJSON(csv) {
var lines = csv.split("\n");
var result = [];
// NOTE: If your columns contain commas in their values, you'll need
// to deal with those before doing the next step
// (you might convert them to &&& or something, then covert them back later)
// jsfiddle showing the issue https://jsfiddle.net/
var headers = lines[0].split(",");
for (var i = 1; i < lines.length; i++) {
var obj = {};
var currentline = lines[i].split(",");
for (var j = 0; j < headers.length; j++) {
obj[headers[j]] = currentline[j];
}
result.push(obj);
}
return result; //JSON
}
function Json2table(obj) {
$("#yourTable").html("");
var largerKey = [];
var maxkeylength = 0;
var rows = Object.keys(obj);
// This part is just to take the row with the higher number of columns in case your table isn´t an square
for (var i = 0; i < rows.length; i++) {
var keys = Object.keys(obj[i]);
if (maxkeylength < keys.length) {
largerKey = keys;
maxkeylength = keys.length;
}
}
///////////////////////////////////////
$("#yourTable").append("<thead>");
for (var i = 0; i < largerKey.length; i++) {
$("#yourTable").append("<th>" + largerKey[i] + "</th>");
}
$("#yourTable").append("</thead>");
for (var i = 0; i < rows.length; i++) {
var keys = Object.keys(obj[i]);
var csvData = "";
for (var j = 0; j < keys.length; j++) {
csvData += "<td>" + obj[i][keys[j]] + "</td>";
}
$("#yourTable").append("<tr>" + csvData + "</tr>");
}
return;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<input type="file" id='yourfile'>
<table id='yourTable'></table>
</html>