DEV Community

ekr990011
ekr990011

Posted on

Importing a CSV (spreadsheet) File with JavaScript

This is a simple example of how to import a CSV (spreadsheet) file and place it into an array of arrays or an array of objects with JavaScript using the FileReader object. The complete code can be found at https://gist.github.com/1337ipJbP7U9mi9cdLngL3g5Napum7tWzM/00dda4ccc5eee8da2a0200fc9708abe7. I put the code in a script tag within an HTML page, so that you can run the code in browser. If you are using Chrome, cntl-O will allow you to open the file with the code. Use the inspect tool to see the console logs.

I had a project where I needed to import a CSV (Comma, Separated, Files) and place the data into an array of objects. There a number of Node packages that work with CSV files, but they all seemed too complicated for my needs. ‘

I had data that looked like:

Image description

and I wanted it in format like this

[{column1: “1”, column2: “2”, column3: “3”}, 
    {column1: “4”, column2: “5”, column3: “6”}]
Enter fullscreen mode Exit fullscreen mode

The key issue was how to import the CSV file. This is where the FileReader object in JavaScript comes in. According to Webopedia FileReader is:

“JavaScript FileReader is an object that reads data from BLOBs and files on the client side. Using JavaScript FileReader lets users read files from their own computer system using a web browser (that is, the client) instead of using the server. Software developers use JavaScript FileReader to reduce the processing burden on servers. This helps prevent websites or applications from running slowly.”
.
.
.
“Another use case for Javascript FileReader is to parse data from a plain text file, like a comma-separated values (CSV) file. This is useful for preparing to upload large amounts of data to a database.”

https://www.webopedia.com/TERM/J/javascript-filereader.html

Before I explain how I used FileReader, let me show you the overall structure of the code

Image description

As you can see the code contains four functions. The first function is openFile, which uses the FileReader object and imports the CSV as a text file. The next function is processData, which converts the CSV into an array or arrays. The arrayToObjects function converts the array of arrays to an array of Objects. The tableCreate function creates a simple HTML table with the CSV data.

The first step was to create a button that allows the user to select a CSV file on their computer. The code that does this is:

This is a pretty standard HTML input button that looks like this on the screen:

Image description

When clicked this button opens a window that allows the user to select a file.

Note that when the button is clicked the ‘openFile’ function is called. The code for this function is:

var openFile = function(event) {
      var reader = new FileReader();
      reader.onload = (event) => {
        this.processData(event.target.result)
      }
        reader.onerror = this.errorHandler;
        // Read file into memory as UTF-8
        // console.log(reader.onload)
        reader.readAsText(event.target.files[0]);
    };

Enter fullscreen mode Exit fullscreen mode

An instance of the FileReader object is created and set equal to the variable “reader”. Then “reader.onlooad” creates an event handler that calls “processData” function.

The code for the processData function that converts the CSV data to an arrays is:

  var processData = function(csv) {
        var allTextLines = csv.split(/\r\n|\n/);
        var lines = [];
        while (allTextLines.length) {
            lines.push(allTextLines.shift().split(','));
        }
        console.log(lines);
        this.arraysToObjects(lines);
        this.tableCreate(lines);
      }

Enter fullscreen mode Exit fullscreen mode

This function first processes the csv by splitting it with a regex expression that matches the line breaks. Then each line is put into the array “lines”. I know the code works but I am not exactly clear how the shift and split function do this. Next the arraysToObjects and the tableCreate functions are called.

In my project I had a specific reason why I needed the data in an array of objects, which is what the arraysToObjects function does.

var arraysToObjects = function(lines) {
        obj = {};
        var i
        var j
        outputArray = []
        for (j=1; j < lines.length; j ++) {
          obj = {};
          for (i = 0; i < lines[0].length; i++) {
            obj[lines[0][i]] = lines[j][i];
          }
        outputArray.push(obj)
        }
      console.log(outputArray)
    };
Enter fullscreen mode Exit fullscreen mode

The key issue here is that the first line of the array is the table headers (Column1, Column2, Column3) and I need to make these the keys for my objects. The line that does this is:

obj[lines[0][i]] = lines[j][i];
Enter fullscreen mode Exit fullscreen mode

So the object key is the left side and the value is the right side.

The key value pairs for each element in one array are put into an object (obj), then this object is pushed onto the outputArray. The outputArray is console logged so you can see the array of objects.

I also decided to create an HTML table of the csv data. The code that does this is:

  function tableCreate(lines) {
    //body reference
    var body = document.getElementsByTagName("body")[0];

    // create elements <table> and a <tbody>
    var tbl = document.createElement("table");
    var tblBody = document.createElement("tbody");

    // cells creation
    // Object.keys(outputArray[0]).length
    for (var rows = 0; rows < lines.length; rows++) {
      // table row creation
      var row = document.createElement("tr");

      for (var col = 0; col < lines[0].length; col++) {
        // create element <td> and text node
        //Make text node the contents of <td> element
        // put <td> at end of the table row
        var cell = document.createElement("td");

        var cellText = document.createTextNode(lines[rows][col]);

        cell.appendChild(cellText);
        row.appendChild(cell);
      }

      //row added to end of table body
      tblBody.appendChild(row);
    }

    // append the <tbody> inside the <table>
    tbl.appendChild(tblBody);
    // put <table> in the <body>
    body.appendChild(tbl);
    // tbl border attribute to
    tbl.setAttribute("border", "2");
  }

Enter fullscreen mode Exit fullscreen mode

Since putting out a table of the data was not the point of this post, I will not explain this code.

I know there are a number of potential issues with this code, but as an indie hacker it did the job I needed. It may not be exactly what you need, but it gives you an idea of how to start if you need to import a csv file.

Top comments (3)

Collapse
 
decker67 profile image
decker

I know the code works but I am not exactly clear how the shift and split function do this.

That's easy . Shift pops the actual first value from the array and returns the value, that is split by ,

Do not use var any more, instead let and const.

Collapse
 
ekr990011 profile image
ekr990011

Yea this code was from a while ago as you can see!

Collapse
 
naucode profile image
Al - Naucode

Thanks, it was a good read, bookmarked, and followed!