Lucee cfquery to a CSV file not formatting correctly

619 Views Asked by At

I am trying to take the result of a query and put it into a CSV file to then email to the user. All of the data in the CSV file is correct, but I'm also getting the HTML elements for some reason. Here is my code:

<cffunction name="ledgerTest" access="remote" >

    <cfquery name="ledgerCheck" datasource="RBDMS_UPDATE">
     SELECT * FROM dbo.OOGNS_Schedules 
    </cfquery>
     <cfoutput>  
                <cfsavecontent variable="myCSV">

                    <div>
                        <table border="1"> 
                            <thead align="center">
                                <th>Job Key</th>
                                <th>INSPECTOR</th>
                                <th>PERMIT USER</th>
                                <th>START DATE</th>
                                <th>END DATE</th>
                            </thead>
                            <cfloop query="ledgerCheck">
                                <tr align="left">
                                    <td>#JobKey#</td>
                                    <td>#Inspector#</td>
                                    <td>#permitUser#</td>
                                    <td>#StartDate#</td>
                                    <td>#EndDate#</td>
                                </tr> 
                            </cfloop>
                        </table>
                    </div>

            </cfsavecontent>
          </cfoutput>  
                <cffile action="write" file="temp/ok.csv" output="#myCSV#" />

</cffunction>

And here is the resulting CSV file (I blacked out peoples email address's):

enter image description here

I think that the issue may have to do with the tag because without it I don't get the data from the query. Without the tag the CSV file contains only my code exactly. Yet, regardless of where I move the tag the result is the same.

2

There are 2 best solutions below

7
Bernhard Döbler On

You write a HTML table to a a file which you call .csv. This feels very wrong. You can write this to a file with the extension .html and open it in Excel. That might work as Excel interpretes HTML tables. If you want a CSV-file you should write your data as you need it. Each column separated by ; (semicolon) and a line break #chr(13)##chr(10)# after each row.

<cfsavecontent variable="myCSV">                 
    <cfloop query="ledgerCheck">#JobKey#;#Inspector#;#permitUser#;#StartDate#;#EndDate##chr(13)##chr(10)#</cfloop>
</cfsavecontent>
1
Cole Perry On

The only issues was that I was using .csv. I changed it from ok.csv to ok.xls and it works fine.