Import CSV to HTML Table - jQuery
Demo and code for how to import csv file to HTML Table using jQuery
by Athil
Posted on 22 Jun 2019 Category: jQuery
Views: 4405
Here I am going to show how to import CSV file to HTML Table using jQuery.
Here I created the script for CSV having Headings Name, Email, Phone Number
DEMO
DOWNLOAD DEMO
Full Demo Code
?<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Demo for converting CVF file to html table</title>
</head>
<body>
<h1> Demo for converting CVF file to html table</h1>
<p> Click <a href="downloads/uploadmultipleleads.csv">here</a> to download sample csv file</p>
<input type="file" id="fileUploadCSV"/>
<input type="button" value="Upload csv" id="btnUpload" />
<table class="table" border = "1" id="tblMultileads">
<tr>
<th>Name</th>
<th>
Email
</th>
<th>Phone Number </th>
</tr>
<tbody id="tbodyLeads">
</tbody>
</table>
</body>
<script type="text/javascript" src="js/jquery.min.js" >
</script>
<script>
$(function () {
var csv = $("#fileUploadCSV").val();
$("#btnUpload").bind("click", function () {
debugger;
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;//regex for Checking valid files csv of txt
if (regex.test($("#fileUploadCSV").val().toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var rows = e.target.result.split("\r\n");
if (rows.length > 0) {
var first_Row_Cells = splitCSVtoCells(rows[0], ","); //Taking Headings
if (first_Row_Cells.length != 3 ) {
alert('Please upload a valid csv ,Colums count not matching ');
return;
}
if (first_Row_Cells[0] != "Name") {
alert('Please upload a valid csv, Check Heading Name');
return;
}
if (first_Row_Cells[1] != "Email") {
alert('Please upload a valid csv, Check Heading Email');
return;
}
if (first_Row_Cells[2] != "Phone_Number") {
alert('Please upload a valid csv, Check heading Phone Number');
return;
}
var jsonArray = new Array();
for (var i = 1; i < rows.length; i++) {
var cells = splitCSVtoCells(rows[i], ",");
var obj = {};
for (var j = 0; j < cells.length; j++) {
obj[first_Row_Cells[j]] = cells[j];
}
jsonArray.push(obj);
}
console.log(jsonArray);
var html = "";
for (i = 0; i < jsonArray.length; i++) {
debugger;
if (jsonArray[i].Name != "") {
html += "<tr id=\"rowitem\"" + i + "><td style=\"display:none;\">" + i + "</td><td> <input type=\"text\" value=\"" + jsonArray[i].Name + "\"> </input> </td>";
html += "<td><input type=\"email\" value= \"" + jsonArray[i].Email + "\"></input></td>";
html += "<td><input type=\"text\" value= \"" + jsonArray[i].Phone_Number + "\" ></input></td>";
}
}
document.getElementById('tbodyLeads').innerHTML = html;
}
}
reader.readAsText($("#fileUploadCSV")[0].files[0]);
}
else {
alert("This browser does not support HTML5.");
}
} else {
alert("Select a valid CSV File.");
}
});
});
function splitCSVtoCells(row, separator) {
return row.split(separator);
}
</script>
</html>