If you are looking to get a solution to parse CSV using Javascript and show CSV file data into HTML table, then you can do it using plain javascript and HTML5 FileReader. Before we begin, you can understand, a comma-separated values (CSV) file is a delimited text file that uses a comma to separate values, so in this coding sample, a CSV file will be selected in HTML5 FileUpload element and will be read using HTML5 FileReader API, then the data will be parsed and showed into HTML table
Let's begin by creating a HTML code to upload a file and call Javascript to parse CSV file.
Select a file: <input type="file" id="myFile">
<button onclick='processFile()'>Process</button>
<table id="myTable"></table>
I have also added empty div with id=dvCSV to show data in it.
Now, let's create the JS function to parse it
function processFile() {
var fileSize = 0;
//get file
var theFile = document.getElementById("myFile");
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
//check if file is CSV
if (regex.test(theFile.value.toLowerCase())) {
//check if browser support FileReader
if (typeof (FileReader) != "undefined") {
//get table element
var table = document.getElementById("myTable");
var headerLine = "";
//create html5 file reader object
var myReader = new FileReader();
// call filereader. onload function
myReader.onload = function(e) {
var content = myReader.result;
//split csv file using "\n" for new line ( each row)
var lines = content.split("\r");
//loop all rows
for (var count = 0; count < lines.length; count++) {
//create a tr element
var row = document.createElement("tr");
//split each row content
var rowContent = lines[count].split(",");
//loop throw all columns of a row
for (var i = 0; i < rowContent.length; i++) {
//create td element
var cellElement = document.createElement("td");
if (count == 0) {
cellElement = document.createElement("th");
} else {
cellElement = document.createElement("td");
}
//add a row element as a node for table
var cellContent = document.createTextNode(rowContent[i]);
cellElement.appendChild(cellContent);
//append row child
row.appendChild(cellElement);
}
//append table contents
myTable.appendChild(row);
}
}
//call file reader onload
myReader.readAsText(theFile.files[0]);
}
else
{
alert("This browser does not support HTML5.");
}
}
else {
alert("Please upload a valid CSV file.");
}
return false;
}
I have explained the Javascript code above line by line in comments.
When the Button is clicked, the ProceeFile JavaScript function is called.
Inside the function, first a check is performed to verify whether the file is a valid CSV or a text file. Then a check is performed to make sure whether the browser supports HTML5 File API.
Once above details are checked, CSV file is parsed , line by line and it's contents are showed in HTML table.
For example, let's consider this is our sample CSV file contents
Here is the sample Gif image of the output
You can also take a look at the JSFilddle
Reading CSV using External API in jQuery or Javascript
You can also use external API like Papa parse to read CSV file, it is an open source, well-maintained project and also free.
Using this API, you can create HTML code as below
<form>
<div>
<label for="files">Upload a CSV formatted file:</label>
<input type="file" id="files" accept=".csv" required />
</div>
<div >
<button type="submit" id="submit" >Submit</button>
</div>
</form>
<table id='myTable'></table>
and after including papaparse.js library in your project, we will be calling a submit callback function to perform parse operation. Our first task is to initialize papa parse.
$('#submit').on("click",function(e){
e.preventDefault();
$('#files').parse({
config: {
delimiter: "auto",
complete: GenerateTable,
},
before: function(file, inputElem)
{
//console.log("Parsing file...", file);
},
error: function(err, file)
{
//console.log("ERROR:", err, file);
},
complete: function()
{
//console.log("Done with all files");
}
});
});
Now, we need to define external function "GenerateTable" to create table and show data
function GenerateTable(results){
var markup = "<table class='table'>";
var data = results.data;
for(i=0;i<data.length;i++){
markup+= "<tr>";
var row = data[i];
var cells = row.join(",").split(",");
for(j=0;j<cells.length;j++){
markup+= "<td>";
markup+= cells[j];
markup+= "</th>";
}
markup+= "</tr>";
}
markup+= "</table>";
$("#myTable").html(markup);
}
That's it, we are done, hope you are read CSV using Javascript, but I will strongly recommend using 1st method which is pure Javascript based.
You may also like to read:
Convert CSV to JSON using Javascript
How to get user location using Javascript / HTML5 Geolocation?
Read PDF file using Javascript
How to remove quotation marks (double quotes) from string using jQuery or Javascript?
How to remove square brackets from string using javascript?
Get image width and height using Javascript and jQuery
How to format JSON date into valid date using javascript or jquery?
How do I remove last comma from string using jQuery or Javascript?