Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 1337ipJbP7U9mi9cdLngL3g5Napum7tWzM/00dda4ccc5eee8da2a0200fc9708abe7 to your computer and use it in GitHub Desktop.
Save 1337ipJbP7U9mi9cdLngL3g5Napum7tWzM/00dda4ccc5eee8da2a0200fc9708abe7 to your computer and use it in GitHub Desktop.
Importing a CSV (spreadsheet) File with JavaScript
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>CSV Import</title>
<input type='file' accept='csv' onchange='openFile(event)'><br>
<script>
var openFile = function(event) {
var reader = new FileReader();
reader.onload = (event) => {
this.processData(event.target.result)
}
reader.onerror = this.errorHandler;
// Read file into memory as UTF-8
// console.log(reader.onload)
reader.readAsText(event.target.files[0]);
}
// processData converts the csv file to an array of arrays
var processData = function(csv) {
var allTextLines = csv.split(/\r\n|\n/);
var lines = [];
while (allTextLines.length) {
lines.push(allTextLines.shift().split(','));
}
console.log(lines);
this.arraysToObjects(lines);
this.tableCreate(lines);
}
// arraysToObjects converts the array or arrays to an array of objects
var arraysToObjects = function(lines) {
obj = {};
var i
var j
outputArray = []
for (j=1; j < lines.length; j ++) {
obj = {};
for (i = 0; i < lines[0].length; i++) {
obj[lines[0][i]] = lines[j][i];
}
outputArray.push(obj)
}
console.log(outputArray)
};
function tableCreate(lines) {
//body reference
var body = document.getElementsByTagName("body")[0];
// create elements <table> and a <tbody>
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
// cells creation
// Object.keys(outputArray[0]).length
for (var rows = 0; rows < lines.length; rows++) {
// table row creation
var row = document.createElement("tr");
for (var col = 0; col < lines[0].length; col++) {
// create element <td> and text node
//Make text node the contents of <td> element
// put <td> at end of the table row
var cell = document.createElement("td");
var cellText = document.createTextNode(lines[rows][col]);
cell.appendChild(cellText);
row.appendChild(cell);
}
//row added to end of table body
tblBody.appendChild(row);
}
// append the <tbody> inside the <table>
tbl.appendChild(tblBody);
// put <table> in the <body>
body.appendChild(tbl);
// tbl border attribute to
tbl.setAttribute("border", "2");
}
</script>
</head>
<body></body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment