Quick and dirty CSV export

Do you always find that you are asked to drop export buttons next to recordsets all the time? We are, all the time. Almost to the point that it is mandatory for us to put an export button in every time we show a recordset over 25 rows.

We wanted an easy way to dump the recordset to a CSV file without too much fussing around so we came up with this little snippet of code that takes care of all the fuss. All you need is our CSV library and a submit button away you go

<!--- Some code that generates a recordset (called qRecordset) --->
<!--- Are we exporting? --->
<cfif structKeyExists(form,"export")>
   <cfset filename="MyCoolExport.csv">

   <cfset oCSV = createObject("component","net.redbd.cfc.csv")>
   <cfset csvExport = oCSV.query2CSV(qRecordset)>
   <cfsetting enablecfoutputonly="true" showdebugoutput="false">
   <cfcontent reset="Yes" type="application/csv">
   <cfheader name="Content-Disposition" value="attachment; filename=#filename#">
   <cfoutput>#csvExport#</cfoutput>
   <cfabort><!--- We don't want any footers etc --->
</cfif>

You will notice that we are looking for the existence of form.export and if we find it, we stop executing the page and start dumping out the CSV file.

If you want extra credit from your users, you can even give your users friendly column names, just pass another two argument when you generate the CSV. They are two lists of colum names, the first are the names used in your recordset the second are the names that you want to appear in your CSV file. Obviously order is important here so make sure you get them matched up

<cfset csvExport = oCSV.query2CSV(qRecordset,
                           "ID,NAME,ACCOUNTMANAGER,COUNTRYCODE,DTLASTUPDATED",
                           "ID,Account Name,Account Manager,Country,Last Updated")>

And that is it, Hopefully this will save you a few minutes this Friday and get you to the pub that little bit sooner.

Cheers,
Lucas.

Time for sharing - CSV read and write library

We've been discussing internally the releasing of some of our useful library code in order to give back to the community that we've got significant amounts of benefit from - Thanks Ray for the blog, thanks daemon for farcry and thanks apache for webserver, linux for my OS and IBM et al for eclipse.

We're currently cleaning up the code a bit for release, but the first piece of code is something that we've had around for quite a while is a solid CSV reading and writing library.

It simplifies the process of creating and reading CSV files that are universally used for simple data transfers.

It is not absolutely complete but it is very functional and allows conversion from:

  • CSV to Query
  • CSV to Array
  • Array to CSV
  • Query to CSV

We use it to great effect for creating super simple exports of queries for reporting.

Hope some people find it useful, and let me know if you find anything that doesn't work how it should.

Cheers, Mark