JSFiddle - React, Tailwind, and code Playground
by Steven Senkus
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/themes/smoothness/jquery-ui.css">
<form enctype="multipart/form-data">
<input id="fileSelect" type="file" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
<input type="file" id="target" accept=".csv" />
<button type="submit">SUBMIT</button>
</form>
<pre style="display: none;" id="csvData">FirstName,LastName,Title,ReportsTo.Email,Birthdate,Description
Tom,Jones,Senior Director,[email protected],1940-06-07Z,"Self-described as ""the top"" branding guru on the West Coast"
Ian,Dury,Chief Imagineer,[email protected],,"World-renowned expert in fuzzy logic design.Influential in technology purchases."</pre>
<table>
<thead>
<tr></tr>
</thead>
<tbody></tbody>
</table>
CSS
table {
background-color: #000;
color: #00bbee;
margin-top: 50px;
text-align: center;
}
table th, table td {
font-size: 14px;
border: 1px solid #fff;
padding: 5px;
}
JavaScript
//var csv is the CSV file with headers
function csvJSON(csv) {
var lines = csv.split("\n");
var result = [];
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; //JavaScript object
//return JSON.stringify(result); //JSON
}
$('form').on('submit', (e) => {
e.preventDefault();
var data = $('#csvData').text();
var dataObj = csvJSON(data);
console.log(dataObj);
// create header
Object.keys(dataObj[0]).forEach(function (item) {
$('table thead tr').append('<th>' + item + '</th>');
});
dataObj.forEach(function (item) {
var $row = $('<tr></tr>');
var cells = '';
Object.keys(dataObj[0]).forEach(function (key) {
$row.append('<td>' + item[key] + '</td>')
});
$('table tbody').append($row)
});
});