Read, Parse and display CSV (Comma separated value) data using Jquery

In this tutorial, you can read the csv file content and display in a textarea with the help of Jquery.

FileReader will fetch the contents from the csv file using the file upload.

To get the csv data, you will need to upload the .csv file. When the csv file is loaded FileReader read the data and show the results.

I am using Jquery FileReader that fetches the contents from the csv file.

The following screenshot displays the UI being displayed in the browser:-


tgl_pic_without_content

Demo Code

Add Folder:-

1. Create new folder – csv

Add File:-

1. Add file in csv folder – index.html

index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
	<head> 
		<meta http-equiv="content-type" content="text/html; charset=utf-8" />
		<meta http-equiv="content-language" content="en" />
		<title>Get CSV Data</title>
		
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
		<script type="text/javascript">
		$(document).ready(function(){
			$("#notification_email_id").change(function(e){
				var ext = $("input#notification_email_id").val().split(".").pop().toLowerCase();
		
				if($.inArray(ext, ["csv"]) == -1){
					alert('Please upload CSV file');
					return false;
				}
					
				if(e.target.files != undefined){
					var reader = new FileReader();
					reader.onload = function(e){
						var csv_val=e.target.result.split("\r\n");				
						var csv_value=""+csv_val+"".split(",");
						var input_data="";
						for(var i=0;i<csv_value.length;i++){
							var temp=csv_value[i];
							var input_data=input_data+""+temp;
						}
						final_input_data = input_data.slice(0, -1);	
						$("#notification_email").val(final_input_data);
					};
					reader.readAsText(e.target.files.item(0));
				}
				return false;
			});	
		});	
		</script>
	</head>
	<body>	
		<table border="0">
			<tr>
				<td><b>How to read data From CSV file using jquery?</b></td>
			</tr>
			<tr>
				<td><textarea class="form-control" name="notification_email" id="notification_email" rows="4" placeholder="CSV file only" cols="40" readonly="readonly" required></textarea></td>
			</tr>
			<tr>
				<td><input name="notification_email_id" id="notification_email_id" type="file" class="" accept=".csv" /></td>
			</tr>
		</table>
	</body>
</html>

The following screenshot displays the CSV file being displayed in the browser:-
tgl_pic_with_content

tgl.csv

Download Link – CSV file

SHARE:

Leave a Reply

Your email address will not be published. Required fields are marked *

*