3

I'm working on a web app for my company that will let us do some image tagging stuff, and I'd like to be able to generates results in the form of a CSV file. I can do this easily enough by dumping the CSV data to a div or something on the page and having the user copy it out. I'd rather have them hit the a generate button and have a CSV file downloaded as though they clicked on a link to the result, so they can more easily just save the file somewhere convenient.

Is it possible to simulate this kind of thing with javascript? I basically want to dynamically generate the file and then let them download it, client side.

2 Answers 2

8

You can create a data: URI with media type text/csv, and either create a link to it, or navigate directly to it, in modern browsers.

It won't work in IE. (IE8 can support data: in limited circumstances which don't help you here.) For that browser at least, you'll need to fall back to cut-n-paste or a server backend.

Sign up to request clarification or add additional context in comments.

1 Comment

Bah. Beat me by 14 seconds ;)
1

I've written a light-weight client-side CSV generator library that might come in handy. Check it out on http://atornblad.se/github/ (scroll down to the headline saying Client-side CSV file generator)

It requires a functioning FileSaver implementation handling calls to window.saveAs(). Check out Eli Grey's solution on http://eligrey.com/blog/post/saving-generated-files-on-the-client-side

When in place, you simply generate and save CSV files on the fly like this:

var propertyOrder = ["name", "age", "height"];

var csv = new Csv(propertyOrder);

csv.add({ name : "Anders",
          age : 38,
          height : "178cm" });

csv.add({ name : "John Doe",
          age : 50,
          height : "184cm" });

csv.saveAs("people.csv");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.