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
<!--- 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
"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.
