Skip to main content
Inspiring
June 8, 2007
Question

Outputting CFQuery to a file?

  • June 8, 2007
  • 3 replies
  • 2275 views
If I'm trying to create a CSV file for importing into Word, how can I do
this? I can get all the fields I want via the query, but am unsure how to
dump that data to a file.

Has anyone done this, and have any suggestions?

Thanks!

    This topic has been closed for replies.

    3 replies

    Inspiring
    June 8, 2007
    I might consider Dan's approach if the dataset was very large, but as we're
    just writing it to a CSv I'm going to ass-u-me that it is not.

    It'd be better to minimise the number of hits one makes to the file system,
    as it's a costly operation.

    I'd capture the data in one fell swoop with <cfsavecontent>, and write ONCE
    to the file.

    One the other hand, it the dataset is big, it would perhaps be costly in
    RAM resources to store the <cfsavecontent> of it in RAM too. That said: if
    that's a consideration, I'd start thinking about getting the DB server to
    write the file directly, rather than involving CF at all.

    --
    Adam
    Inspiring
    June 8, 2007
    Here is another way.

    <cfif procedures.recordcount gt 0>

    <cffile action="write" nameconflict="overwrite"
    addnewline="no" output=""
    file="d:\dw\dwweb\work\#ProcFileName#">

    <cfoutput query="procedures">
    <cffile action="append"
    file="d:\dw\dwweb\work\#ProcFileName#"
    output="#case_id#|#mrm#|#dpf#|#procdate#|#pdt_code#|#replace(pdt_name, chr(10), ' ', 'all')#|#replace(comments, chr(10), ' ', 'all')#|#prisurg#|#priproc##chr(13)#">
    </cfoutput>

    </cfif>

    Inspiring
    June 8, 2007
    Steve,

    One approach would be similar to the following
    <cfquery name="myQuery">
    ...
    </cfquery>
    <cfsavecontent variable="myCSV">
    Field1, Field2, Field3
    <cfoutput query="myQuery">
    #field1#,#field2#,#field3##Chr(13)#
    </cfoutput>
    </cfsavecontent>
    <cffile action="write" file="file.csv" output="#myCSV#"/>

    This would output your query in a CSV-friendly format and then write the content (saved by the cfsavecontent tag) of the myCSV variable to a file (you could also incorporate the use of a cfcontent tag to save the contents to a CSV file).

    I'm not sure how much detail you're looking for from your post but hope this helps get you going.

    Best,
    Craig