• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
seegatesite header

Seegatesite.com

Seegatesite.com - Programming Tutorial , Sharing , How and Learn Together

  • TOOLS
    • Bootstrap Navbar Online Generator
    • Customize Sidebar Menu Bootstrap 3
    • Bootstrap Demo
  • ADVERTISE
  • CATEGORIES
    • Android
    • Blogging Tips
    • Database
    • CSS
    • Info Gadget
    • Javascript
    • Linux
    • PHP
    • Various
    • WordPress
  • Q&A
  • PHP
  • JAVASCRIPT
  • JQUERY
  • ANGULAR
  • WORDPRESS
  • SEO
  • REACT
🏠 » Javascript » Tutorial Read And Write CSV File With Javascript

Tutorial Read And Write CSV File With Javascript

By Sigit Prasetya Nugroho ∙ April 23, 2020 ∙ Javascript ∙ Leave a Comment

Share : TwitterFacebookTelegramWhatsapp

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

  • 1 Creating CSV Files in Javascript
    • 1.1 How To
    • 1.2 Problem
    • 1.3 The solution
  • 2 Reading Javascript CSV File
    • 2.1 Read CSV files using Javascript
    • 2.2 Using the Javascript plugin : Papa Parse.

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

Create Array Javascript

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)?

Array Of Object Example Data

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:

Array Of Object How To Export Data Into Csv File In Javascript

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:

Read Csv File With Native Javascript

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.

Another Javascript Related Post :

  • Adept Using Datatables Plugin In 10 Minutes For Beginners (Tutorial)
  • The Using Of Reactstrap And React-Table, Suitable For Beginners
  • Tutorial Create Simple Block UI Using React JS
  • How To Implement Login Page And Protected Route ReactJS
  • Complete Tutorial React Router Dom For Beginners (Easy-To-Understand)
  • The Right Way Understanding React Lifecycle For Beginners

Avatar for Sigit Prasetya Nugroho

About Sigit Prasetya Nugroho

This site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.

Reader Interactions

Leave a Reply Cancel reply

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

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Welcome to my Home,

Avatar for Sigit Prasetya NugrohoThis site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.



Popular Articles

Checked checkbox AdminLTE Bootstrap in Jquery

November 4, 2014 By Sigit Prasetya Nugroho 7 Comments

Simple create date format validation with jqueryUI

December 21, 2014 By Sigit Prasetya Nugroho Leave a Comment

Create Simple Progress Bar for Fake Online Generator with Jquery

January 10, 2015 By Sigit Prasetya Nugroho Leave a Comment

22+ Coolest Free Jquery Plugin For Premium Theme

October 3, 2015 By Sigit Prasetya Nugroho Leave a Comment

Easy Build Your Anti Copy Paste Plugin

October 6, 2015 By Sigit Prasetya Nugroho Leave a Comment

Popular Tags

adminlte (15) adsense (13) adsense tips (4) affiliate amazon (13) amazon (12) Android (8) angular (16) angular 4 (12) angular 5 (4) asin grabber (3) Bootstrap (27) codeigniter (5) create wordpress theme (5) crud (8) css (6) free wordpress theme (7) google adsense (4) imacros (4) increase traffic (6) jquery (34) laravel (10) laravel 5 (5) learn android (5) modal dialog (5) mysql (6) nodeJs (4) optimize seo (4) pdo (6) php (30) plugin (53) pos (7) Publisher Tips (5) react (3) Reactjs (7) SEO (37) theme (17) tutorial angular (5) tutorial angular 4 (6) tutorial javascript (10) tutorial javascript beginners (4) twitter (3) widget (3) wordpress (18) wordpress plugin (13) XMLRPC (5)




  • About
  • Contact Us
  • Disclaimer
  • Privacy Policy
  • Terms and Conditions

©2021 Seegatesite.com