ExploreOurteamtrainingCourses (3)

This article was originally published on the halistechnology.com and written by Chris Grimes.

Do you know what annoys me? When I have my data in a web application and I can’t get it out. And if you’re not giving your users a way to export their data, then they’re annoyed too.

Today I’m going to show you how simple it is to provide CSV downloads in your application.

All that’s needed is a little Javascript and HTML. You don’t need a fancy $2,000 control suite or any server-side code.

First, we need some data. For this example we will turn an array of objects into a CSV download for the user:

Now we need a function that will take any array of objects and create CSV data:

First the function loops through the keys on one of the objects to create a header row, followed by a newline. Then we loop through each object and write out the values of each property.

Here’s what you end up with:

Now we need a function that will take this data and turn it into a CSV file for download:

This function takes the CSV we created and prepends a special string that tells the browser that our content is CSV and it needs to be downloaded:

So now we have:

We set the href attribute on our link to the above string. We also set the download attribute on our link to the filename we want to see for our download stock-data.csv

Then in our html we have a simple link that we can use to kick off things and test it out:

And when you click this link here’s what should happen:

You should get a download in the browser called stock-data.csv and then when you open it, we see the data in the expected table format.

The meat of this example happens in less than 50 lines of code. The code loops through your objects generically, so it doesn’t matter what properties are on your objects. If each object had 100 or 3 properties it would work just as well.

It’s also a nifty trick that you can create a download so easily in the browser. Not all developers know that you can do that. In fact, that same special string can be modified to allow other types of downloads.

Here’s the full example if you want to play with it:

Chris Grimes
Chris Grimes is the founder of Halis Technology, which offers software consulting and training in the St. Louis area.
0
JavaScript

Comments