How to read data from *.CSV file using JavaScript?


In this article, we are going to learn how to read data from *.CSV file using JavaScript.

To convert or parse CSV data into an array, we need JavaScript’s FileReader class, which contains a method called readAsText() that will read a CSV file content and parse the results as string text.

If we have the string, we can create a custom function to turn the string into an array.

To read a CSV file, first we need to accept the file.

Now let’s see how to accept the csv file from browser using HTML elements.

Example

Following is the example program to accept the csv file from the browser.

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <form id="myForm"> <input type="file" id="csvFile" accept=".csv" /> <br /> <input type="submit" value="Submit" /> </form> </body> </html>

We can now choose a csv file that need to be read.

Now let’s write a JavaScript code that read the csv file chosen.

Example

Following is the example program, which accept and reads the csv file.

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <form id="myForm"> <input type="file" id="csvFile" accept=".csv" /> <br /> <input type="submit" value="Submit" /> </form> <script> const myForm = document.getElementById("myForm"); const csvFile = document.getElementById("csvFile"); myForm.addEventListener("submit", function (e) { e.preventDefault(); const input = csvFile.files[0]; const reader = new FileReader(); reader.onload = function (e) { const text = e.target.result; document.write(text); }; reader.readAsText(input); }); </script> </body> </html>

Updated on: 08-Sep-2023

35K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements