I recently wanted to add the ability to export CSV files from my little Grails app directly to the browser with one of those "Save As…" numbers. Makes it very easy for clients to save a copy of their addressbook directly to their local disk, and reimport it later on.

I’m using opencsv for the heavy lifting so the CSV bit was a snack. The tricky bit was getting the browser to popup as a "Save As".  Messing with content/type didn’t help me, so it was time to do some researching…. and there’s just a little magic required which Grails controllers make very simple.

So here’s the magic strings you’re looking for.

response.setHeader("Content-disposition", "attachment; filename=" +
    session.userid + ".csv");
render(contentType: "text/csv", text: sw.toString());

And that will give you:

Dynamic File Creation Screenshot

Giddy up. Just what I was after…