Reply to topic
Coding Tip: Export Query Results to Excel
JeanR
HostMySite Marketing

Joined: 28 Feb 2005
Posts: 86
Reply with quote
If you have ever wanted to export the results of a query displayed on your website into an excel spreadsheet, here is a simple way to do so. One of the key items to note in the following coding example is that you should not change the space in between fields in the CFSet, otherwise you risk the export not working.

Code:
<CFQUERY NAME="GetData" DATASOURCE="Name">
    SELECT fielda, fieldb, fieldc
    FROM tablename
    WHERE conditions
</CFQUERY>
<CFSET tempfile = "C:\websites\directoryname\data.xls">
<CFSET output = "">
<CFSET output = output & "fielda fieldb fieldc">
<CFFILE ACTION="WRITE"
    FILE="#tempfile#"
    OUTPUT="#output#">
<CFLOOP QUERY="GetData">
    <CFSET output = "">
    <CFSET output = output & "#fielda#   #fieldb#   #fieldc#>
    <CFFILE ACTION="APPEND"
        FILE="#tempfile#"
        OUTPUT="#output#">
</CFLOOP>
<CFCONTENT TYPE="application/msexcel" FILE="#tempfile#">
Typo
psenn


Joined: 01 Dec 2005
Posts: 5
Reply with quote
I'm very interested in doing this.
You forgot to close quote at the end of #fieldc#.

Although this creates an xls file, it doesn't create three columns.
POI
psenn


Joined: 01 Dec 2005
Posts: 5
Reply with quote
There is a free podcast at the cfUnited blog, and one is titled
"Jeremy Lund - Another Look at Microsoft Office Using Apache Jakarta POI", which is a method of working directly with Microsoft Office documents such as Word and Excel.

I don't know if HMS uses this feature, but it apparently comes with CF.
eschaefer


Joined: 27 Mar 2007
Posts: 1
Reply with quote
Extra notes:

Adding the following to the code will output the file as an xls, otherwise your browser will see the incoming file as the page name (ie page.cfm)

Code:

<cfheader name="Content-Disposition" value="filename=#tempfile#">


Also putting tabs between elements will instead of spaces will create new columns.
bobclingan
Forum Regular

Joined: 16 Sep 2004
Posts: 271
Location: Abingdon, MD
Reply with quote
You don't even need to write a file to disk you can just set headers and then do your normal output of what you want:

<cfheader name="Content-Disposition" value="attachment; filename=#currentDisplayReport#.xls">
<cfcontent type="application/vnd.ms-excel">

You can then output data as an html table or for more customization use Microsoft's XML format.

Or just use the POI solution mentioned by the other poster.
Coding Tip: Export Query Results to Excel
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
All times are GMT  
Page 1 of 1  

  
  
 Reply to topic