DEV Community

ekr990011
ekr990011

Posted on

2

Exporting CSV File (spreadsheet) with JavaScript

I was working on a project where I needed to export a CSV (Comma Separated Values) file using JavaScript. I was feeling lazy and I thought I could find a nice Node package that would do most of the work for me. All the Node packages I found seemed very powerful, with lots of options, however it also appeared that they would be hard to figure out.

The problem with using a Node package or say a gem in ruby that is very powerful is that if they do not do exactly what you want, then you can spend hours if not days trying to figure out how to make them work for you. As a result, I made up my mind that it would be easier to just write the code myself.

I had data that looked like this on my web app:

Image description

(No these are not my Bitcoin address – lol, this from a list of the richest Bitcoin address)

And I wanted it to put out something that looked like this, when open by a spreadsheet:

Image description

(Screenshots from my app CryptoChecker – https://www.1337ipjbp7u9mi9cdlngl3g5napum7twzm.com)

In my case, I had the data I wanted to put out to a CSV file in an Array of Objects. Because the app is javascript, if the user closes the app all the data is lost. The public addresses are quite long and can be a pain to put into the app, so the user may want to store this information.

I had written similar code in React, Jquery and had done some CSV work in Ruby. So I put my nose to the grindstone and dug into writing the code. I quickly realized that the file management tool was going to be the key issue. In Ruby there are some excellent file management tools, however this is less true in Java Script.

Despite this I found a nice Node module, FileSaver.js (click here for FileSaver npm page), that would save the output file as a CSV and allows the user to name their file easily. After installing the FileSaver node module and importing it, the key line of code is:

var blob = new Blob([csv], {type: "text/plain;charset=utf-8"});
  saveAs(blob, "yourcsv.csv");
Enter fullscreen mode Exit fullscreen mode

A Blob is just a chunk of data and the name comes from SQL databases and means “Binary Large Object”. As you can see you can name the file (yourcsv.csv) and determine the file type. Once I got this working, then I just need to get my Array of Objects into the right format.

I rewrote my actual code to make this post more clear for the reader. I start with a simple Array of Objects:

const arrayOfObjects = [{column1: "1", column2: "2", column3: "3"},{column1: 4, column2: 5, column3: 6}]
Enter fullscreen mode Exit fullscreen mode

From here the code is fairly straight forward to convert the arrayOfObjects to a csv:

arrayOfObjects.map((row) => {
csv += `\r\n ${row.column1}, ${row.column2}, ${row.column3}`
})
Enter fullscreen mode Exit fullscreen mode

Note the \r\n is a carriage return + line feed. This starts a new row. If you console log the csv, you get (if you add the keys as the headers).

column1, column2, column3, 
1, 2, 3
4, 5, 6
Enter fullscreen mode Exit fullscreen mode

`
This is exactly what I wanted.

FileSaver.js worked perfectly and downloaded the file yourcsv.csv.

Here is the github gist (https://gist.github.com/1337ipJbP7U9mi9cdLngL3g5Napum7tWzM/fd9b8aafbba79dc76971e892c2c82ec0) of the code.

In order to provide you the code in a format you could easily play with, I had the bright idea to just put this example code in some script tags inside a web page and then to run it locally in Chrome browser (note ctr O allows you to open a local file). Unfortunately, this made it hard to work with the FileSaver.js Node module. You cannot use “Import” inside of script tags.

As a result, I had to go to the github page for FileSaver.js (https://github.com/eligrey/FileSaver.js), copy the “FileSaver.js” file in the “dist” folder and paste it into a new file in the same directory as my code. The FileSaver.js is then imported using a “script src=” tag on line 6, as seen below

<script src="./filesaver.js"></script>

You will need to do this also if you want to play with the code.

There may be a better way to put out a CSV file, however it is good enough for an Indie Hacker. If you know a better way, let me know in the comments.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️