Comma Separated Value or CSV is the data format that we encounter most frequently to import and input data into a massive database. CSV used the ASCII standard file, where each record separated by a comma delimiter (,) or semicolon (;). In this simple tutorial, I share tips on how to read and write CSV files using javascript.
The idea of this tutorial is that we create export and import data files in CSV format using JavaScript.
Table of Contents
Creating CSV Files in Javascript
To create a CSV file, we need a data source that creates a CSV file. The data source that we encounter most often is an array of data types. Besides that, there is also a collection of objects in an array. See the following code to create a CSV file in Javascript.
How To
For example, we have the following array:
1 2 3 4 5 6 | let arrayHeader = ["Name","Country","Email"]; let arrayData[] = ["Sigit Prasetya","Indonesia","sigit@gmail.com"]; arrayData[] = ["Song Hye Kyo","South Korea","songsong@gmail.com"]; arrayData[] = ["Andy Lau","Hongkong","andyLau@gmail.com"]; arrayData[] = ["Enji Shaun","United State","shaun2@gmail.com"]; arrayData[] = ["Azumi","Japan","azumiK@gmail.com"]; |
from the example above we have data like the following image
To create a CSV file using the above data, we use the following CSV export function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | const export_csv = (arrayHeader, arrayData, delimiter, fileName) => { let header = arrayHeader.join(delimiter) + '\n'; let csv = header; arrayData.forEach( array => { csv += array.join(delimiter)+"\n"; }); let csvData = new Blob([csv], { type: 'text/csv' }); let csvUrl = URL.createObjectURL(csvData); let hiddenElement = document.createElement('a'); hiddenElement.href = csvUrl; hiddenElement.target = '_blank'; hiddenElement.download = fileName + '.csv'; hiddenElement.click(); } |
A brief description :
Back again to the initial concept of CSV, CSV files have a fairly simple structure, which is a collection of data separated by commas and line breaks. Same as export_csv function above.
A collection of arrays is combined into a sentence using the join method with a comma (,) separator. And the sentences are combined into a paragraph separated by a line break (\n).
Second example
How do we create a CSV file if the array is a collection of objects (or we often call them arrays of objects)?
For example, we have an array of data like the following.
1 2 3 4 5 6 7 | let arrayHeader = ["Name","Country","Email"]; let arrayData = [] arrayData[0] = { name : "Sigit", country : "Indonesia", email : "sigit@gmail.com"}; arrayData[1] = { name : "Joana", country : "Brazil", email : "Joana@gmail.com"}; arrayData[2] = { name : "Albert", country : "Mexico", email : "albert@gmail.com"}; arrayData[3] = { name : "Nuuna", country : "South Korea", email : "Nuuna@gmail.com"}; arrayData[4] = { name : "Aroon", country : "Irlandia", email : "aroon@gmail.com"}; |
When we test through the console window, we see the following data format as below:
You can modify the export_csv function slightly as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | function export_csv(arrayHeader, arrayData, delimiter, fileName) { let header = arrayHeader.join(delimiter) + '\n'; let csv = header; arrayData.forEach( obj => { let row = []; for (key in obj) { if (obj.hasOwnProperty(key)) { row.push(obj[key]); } } csv += row.join(delimiter)+"\n"; }); let csvData = new Blob([csv], { type: 'text/csv' }); let csvUrl = URL.createObjectURL(csvData); let hiddenElement = document.createElement('a'); hiddenElement.href = csvUrl; hiddenElement.target = '_blank'; hiddenElement.download = fileName + '.csv'; hiddenElement.click(); } |
A brief description :
The script differences are in the following code
1 2 3 4 5 6 7 | let row = []; for (key in obj) { if (obj.hasOwnProperty(key)) { row.push(obj[key]); } } csv += row.join(delimiter)+"\n"; |
We take the value of an object, and then we combine it into an array.
Just like the first method, the next step is to convert the array into a string data type and separate each data using the specified delimiter.
Problem
At this point, we have succeeded in creating a CSV file using javascript. But some problems often occur, namely, when the data that converted to CSV has the same character as a delimiter. For example, both have a comma (,), double quotation marks “or one quotation marks,” then the CSV format will be messy when opened using an imported application that is already available.
The solution
To overcome this problem, what I often do is get rid of unwanted special characters with the regex function. For example, I want the character just string, number, and space only. I used to use the following function
Remove unwanted special characters in Javascript
1 2 3 4 5 6 | function removeSpecialChar(str){ if(str == null || str == ''){ return ''; } return str.replace(/[^a-zA-Z0-9 ]/g, '') } |
Reading Javascript CSV File
After successfully writing CSV files using javascript, of course, we also want to read CSV files using javascript via the input form. There are several ways to read CSV files; you can create native javascript scripts to read CSV files or use the javascript plugin. Let’s start the tutorial:
Read CSV files using Javascript
Copy the following program code
HTML Code :
1 | <input type="file" id="uploadfile" onChange="readImage(this)"> |
Javascript Code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | var obj_csv = { size:0, dataFile:[] }; function readImage(input) { console.log(input) if (input.files && input.files[0]) { let reader = new FileReader(); reader.readAsBinaryString(input.files[0]); reader.onload = function (e) { console.log(e); obj_csv.size = e.total; obj_csv.dataFile = e.target.result console.log(obj_csv.dataFile) parseData(obj_csv.dataFile) } } } function parseData(data){ let csvData = []; let lbreak = data.split("\n"); lbreak.forEach(res => { csvData.push(res.split(",")); }); console.table(csvData); } |
Run the above code to see the results through the console window as follows:
Using the Javascript plugin : Papa Parse.
A plugin that is quite well known is Papa Parse. Maybe the name sounds a little unique, but it’s handy and works well. You don’t need to bother creating your script, download and use it. Okay, let’s start
Download parse papa here.
Copy the parse papa and JQuery scripts as follows
1 2 | <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="papaparse.min.js"></script> |
Use the following code to parse csv file :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | $('#inputFile').parse({ config: { delimiter: "auto", complete: displayHTMLTable, }, before: function(file, inputElem) { console.log("Parse file : ", file); }, error: function(err, file) { console.log("Error:", err, file); }, complete: function(results) { console.log("Finished:", results.data); } }); |
Interested in javascript tutorials , read “Javascript tutorial from zero to expert“
The method is quite easy, but it should be understood that to be able to use the plugin requires several additional plugins such as JQuery so that the plugin runs well
Thus a brief tutorial on writing and reading CSV files using Javascript, Hopefully, useful and do not be lazy to try.
Thank you very much! After much searching and trying different codes this is the best code I found using just js to read local file into an array (map?).
thanks again