Skip to content

Instantly share code, notes, and snippets.

@edwardlorilla
Created June 3, 2021 15:28
Show Gist options
  • Save edwardlorilla/5ba16debded977949f55722c1e889498 to your computer and use it in GitHub Desktop.
Save edwardlorilla/5ba16debded977949f55722c1e889498 to your computer and use it in GitHub Desktop.
【JAVASCRIPT】Read CSV file with File API
<input type="file" name="select" id="select" />
<div id="result"></div>
// Check if it supports File API
if (window.File) {
var result = document.getElementById ('result');
var select = document.getElementById ('select');
// When a file is selected
select.addEventListener ('change', function (e) {
// Get information about the selected file
var fileData = e.target.files [0];
var reader = new FileReader ();
// When file reading fails
reader.onerror = function () {
alert ('Failed to read file')
}
// When the file is read successfully
reader.onload = function () {
// Make an array in units of rows
var lineArr = reader.result.split ('\n');
// Make a two-dimensional array of rows and columns
var itemArr = [];
for (var i = 0; i <lineArr.length; i ++) {
itemArr [i] = lineArr [i] .split (',');
}
// Output as table
var insert ='<table border="1">';
for (var i = 0; i <itemArr.length; i++) {
itemArr[i] = lineArr[i] .split (',');
}
for (var i = 0; i <itemArr.length; i++) {
insert +='<tr>';
for (var j = 0; j <itemArr [i] .length; j++) {
insert +='<td>';
insert += itemArr[i][j];
insert +='</td>';
}
insert +='</tr>';
}
insert +='</table>';
result.innerHTML = insert;
}
// Perform file read
reader.readAsText (fileData);
}, false);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment