Exporting Data to Excel – ColdFusion

Exporting data to an Excel file using ColdFusion is not a difficult task. What makes it easy is Excel’s ability to open CSV (Comma Separated Value) files.

CSV files have a very simple format, each line is a record, and fields are separated by commas. You do not need to know this to successfully export to Excel, the script below will give you a good enough explanation on how to accomplish this:

<cfsetting enablecfoutputonly="yes"> <!--- Required for CSV export to function properly --->
<cfset delim = 44> <!--- Use a comma for a field delimitter, Excel will open CSV files --->

<cfcontent type="application/msexcel">
<cfheader name="Content-Disposition" value="filename=filename.csv">

<!--- Output Column Headers --->
<cfoutput>Column Header 1#chr(delim)#Column Header 2#chr(delim)#</cfoutput>

<cfoutput>#chr(13)#</cfoutput> <!--- line break after column header --->

<!--- Spill out data from a query --->
<cfloop query="mydbquery"><cfoutput>#dbfield1##chr(delim)##dbfield2#</cfoutput></cfloop>