How to create a csv file in javascript and get the “save as”-dialog

Long headline! Anyway, this is a problem I’ve encountered more than once. When exporting data from a webpage to a .csv file I usaually create it on the server side using a servlet.

However, If the data is already stored in the browser, you don’t want an extra server request (especially if you’ve manipulated the data on the client).

The first lead came from this post. It explains how to open a separate window with csv content. But how to get the “Save As” dialog? After some searching I found tips about using “data URL” and finally found the solution.

The essentials of my test code:

function loadLinkButton(){
  var btn = document.getElementById("linkButton");
  var axx = document.getElementById("ax");
  // I used this online encoder to create the data url.
  // axx.href = 'data:text/csv;base64,MTsyOzQ=';  // This was my first test, not having the encoder. 
  axx.href = 'data:text/csv;base64,'+Base64.encode("3;2;1");} // I used the javascript encoder from this page.
}

<body> 
<a id="ax" href="">test</a>
<button id="linkButton" onclick="loadLinkButton();">asdf</button>
</body>

So basically, pressing the “asdf” button creates the data URL and then the link “test” opens the csv (with save-as dialog). Havn’t tried it in IE, but I’ve read that it’s not going to work.

Questions? Feedback? Feel free to comment!

About these ads

4 Responses to “How to create a csv file in javascript and get the “save as”-dialog”

  1. seotons 3.0 Says:

    Thank, but under firefox it loads directly in .part file :)

  2. Rahul Says:

    nice post… useful for me. can you give me the code for extracting meta tag of any given url..

    • self Says:

      You mean like for analyzing web page content with something like javascript? Sorry, never did that.. I’ve worked more with creating web-applications for control, logging systems and such. And right now I only do C-programming :)

      Try and google it! The code is probably out there somewhere..

  3. yanbing Says:

    Reblogged this on Yanbingms's Blog and commented:
    How to create a csv file in javascript and get the “save as”-dialog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

%d bloggers like this: