Display CSV data in HTML Table in JavaScript

This article shows you how to upload a CSV file and display CSV data in HTML table. You will also see CSV file data displayed in a Bootstrap table.

Overview

A CSV is a comma-separated values file, that allows data to be saved in a tabular format. It is a plain text file that contains a list of data. These files are often used for exchanging data between different applications.

Sometimes we are required to show the CSV file data in HTML table format. So here we will learn to display CSV file data in a plain HTML table and in a Bootstrap table using Javascript. We will use the readAsBinaryString() method of FileReader class to read the CSV file. Now let’s assume we have a CSV file (Employee.csv) like the below:

Employee.csv

Employee Id, Employee Name, Age, Email Id, Date of Joining
101,Rahul Singh,25,[email protected],20-08-2014
102,Neeraj Kumar,30,[email protected],05-01-2012
103,Raj Kumar Yadav,27,[email protected],15-12-2017

Display CSV file in HTML table using Javascript

Displaying the CSV file data into an HTML table is very simple. First, we read the CSV data using the readAsBinaryString() method of FileReader class and convert them into a JSON format. After that, iterate the converted JSON data and display them into HTML Table. See the complete code for it below-

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">  
	<title>CSV to HTML Table | Javacodepoint</title>
  </head>
  <body>
  	<h2>Upload a CSV file to display in HTML Table</h2>
	<!-- Input element to upload an csv file -->
    <input type="file" id="file_upload" />
    <button onclick="upload()">Upload</button>	
    <br>
    <br>
	<!-- table to display the csv data -->
	<table id="display_csv_data" border="1"></table>
    <script>
	
      // Method to upload a valid csv file
	  function upload() {
		var files = document.getElementById('file_upload').files;
		if(files.length==0){
		  alert("Please choose any file...");
		  return;
		}
		var filename = files[0].name;
		var extension = filename.substring(filename.lastIndexOf(".")).toUpperCase();
		if (extension == '.CSV') {
			//Here calling another method to read CSV file into json
			csvFileToJSON(files[0]);
		}else{
			alert("Please select a valid csv file.");
		}
	  }
	  
	  //Method to read csv file and convert it into JSON 
	  function csvFileToJSON(file){
		  try {
			var reader = new FileReader();
			reader.readAsBinaryString(file);
			reader.onload = function(e) {
				var jsonData = [];
				var headers = [];
				var rows = e.target.result.split("\r\n");				
				for (var i = 0; i < rows.length; i++) {
					var cells = rows[i].split(",");
					var rowData = {};
					for(var j=0;j<cells.length;j++){
						if(i==0){
							var headerName = cells[j].trim();
							headers.push(headerName);
						}else{
							var key = headers[j];
							if(key){
								rowData[key] = cells[j].trim();
							}
						}
					}
					
					if(i!=0){
						jsonData.push(rowData);
					}
				}
				 
				//displaying the json result into HTML table
				displayJsonToHtmlTable(jsonData);
				}
			}catch(e){
				console.error(e);
			}
	  }
	  
	  //Method to display the data in HTML Table
	  function displayJsonToHtmlTable(jsonData){
		var table=document.getElementById("display_csv_data");
		if(jsonData.length>0){
			var headers = Object.keys(jsonData[0]);
			var htmlHeader='<thead><tr>';
			
			for(var i=0;i<headers.length;i++){
				htmlHeader+= '<th>'+headers[i]+'</th>';
			}
			htmlHeader+= '<tr></thead>';
			
			var htmlBody = '<tbody>';
			for(var i=0;i<jsonData.length;i++){
				var row=jsonData[i];
				htmlBody+='<tr>';
				for(var j=0;j<headers.length;j++){
					var key = headers[j];
					htmlBody+='<td>'+row[key]+'</td>';
				}
				htmlBody+='</tr>';
			}
			htmlBody+='</tbody>';
			table.innerHTML=htmlHeader+htmlBody;
		}else{
			table.innerHTML='There is no data in CSV';
		}
	  }
    </script>
  </body>
</html>

OUTPUT:

Upload CSV file to display in HTML table

Display CSV file in Bootstrap table using Javascript

Now here, we are going to display the CSV file data into a Bootstrap table. To use bootstrap, we have to include its library in the HTML document. So include the below library inside <head> tag of your HTML document:

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>

In this example, we use the same code like above, only we use .table, .table-bordered, .table-striped (bootstrap table class) to convert the plain HTML table into the Bootstrap table. See the complete code below:

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">  
	<title>CSV to Bootstrap Table | Javacodepoint</title>
	<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
	<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  </head>
  <body>
  <div class="container">
  	<h3>Upload a CSV file to display in Bootstrap Table</h3>
	<!-- Input element to upload an csv file -->
    <input type="file" id="file_upload" />
    <button onclick="upload()" class="btn btn-primary">Upload</button>	
    <br>
    <br>
	<!-- table to display the csv data -->
	<table class="table table-bordered table-striped" id="display_csv_data"></table>
 </div>
    <script>
	
      // Method to upload a valid csv file
	  function upload() {
		var files = document.getElementById('file_upload').files;
		if(files.length==0){
		  alert("Please choose any file...");
		  return;
		}
		var filename = files[0].name;
		var extension = filename.substring(filename.lastIndexOf(".")).toUpperCase();
		if (extension == '.CSV') {
			//Here calling another method to read CSV file into json
			csvFileToJSON(files[0]);
		}else{
			alert("Please select a valid csv file.");
		}
	  }
	  
	  //Method to read csv file and convert it into JSON 
	  function csvFileToJSON(file){
		  try {
			var reader = new FileReader();
			reader.readAsBinaryString(file);
			reader.onload = function(e) {
				var jsonData = [];
				var headers = [];
				var rows = e.target.result.split("\r\n");				
				for (var i = 0; i < rows.length; i++) {
					var cells = rows[i].split(",");
					var rowData = {};
					for(var j=0;j<cells.length;j++){
						if(i==0){
							var headerName = cells[j].trim();
							headers.push(headerName);
						}else{
							var key = headers[j];
							if(key){
								rowData[key] = cells[j].trim();
							}
						}
					}
					
					if(i!=0){
						jsonData.push(rowData);
					}
				}
				 
				//displaying the json result into table
				displayJsonToTable(jsonData);
				}
			}catch(e){
				console.error(e);
			}
	  }
	  
	  //Method to display the data in Table
	  function displayJsonToTable(jsonData){
		var table=document.getElementById("display_csv_data");
		if(jsonData.length>0){
			var headers = Object.keys(jsonData[0]);
			var htmlHeader='<thead><tr>';
			
			for(var i=0;i<headers.length;i++){
				htmlHeader+= '<th>'+headers[i]+'</th>';
			}
			htmlHeader+= '<tr></thead>';
			
			var htmlBody = '<tbody>';
			for(var i=0;i<jsonData.length;i++){
				var row=jsonData[i];
				htmlBody+='<tr>';
				for(var j=0;j<headers.length;j++){
					var key = headers[j];
					htmlBody+='<td>'+row[key]+'</td>';
				}
				htmlBody+='</tr>';
			}
			htmlBody+='</tbody>';
			table.innerHTML=htmlHeader+htmlBody;
		}else{
			table.innerHTML='There is no data in CSV';
		}
	  }
    </script>
  </body>
</html>

OUTPUT:

Upload CSV to display in Bootstrap table

Conclusion

In this article, you have learned how to display/show the CSV file data into an HTML table and Bootstrap table using Javascript.

Related articles

Share with friends

Leave a Comment

Your email address will not be published.