<!--- Create out data query (you would be using this as your database query, for demonstration, I have to build it manually). ---> <cfset qData = QueryNew( "" ) /> <!--- Add Query columns. ---> <cfset QueryAddColumn( qData, "id", "cf_sql_integer", ListToArray( "1,2,3,4,5" ) ) /> <cfset QueryAddColumn( qData, "name", "cf_sql_varchar", ListToArray( "Ann,Kit,Libby,Jane,Beth" ) ) /> <cfset QueryAddColumn( qData, "pet_name", "cf_sql_varchar", ListToArray( "Cutie,""Honey"",Baby,Sugar,Sweetness" ) ) /> <!--- Now, let's create our array of row data. We are going to create a CSV data set where each array index is its own row of data. ---> <cfset arrData = [] /> <!--- Now, we are going to start off by building a row of column headers. Since we have (potentially) a lot of columns, we are going to be using the query's column list. Let's first break that up in to an array do its faster to navigate. ---> <cfset arrColumns = ListToArray( qData.ColumnList ) /> <!--- Ok, now lets create an array for our header data. ---> <cfset arrRow = [] /> <!--- Loop over columns. ---> <cfloop index="strValue" array="#arrColumns#"> <!--- Add prepared CSV value to row array. ---> <cfset ArrayAppend( arrRow, PrepareCSVValue( strValue ) ) /> </cfloop> <!--- Now that we have built up our row data, let's collapse it and add it to our master data array. ---> <cfset ArrayAppend( arrData, ArrayToList( arrRow ) ) /> <!--- Now that we have a header row out of the way, we have to basically do the same thing for the actual data rows. ---> <cfloop query="qData"> <!--- Create the array for this row. ---> <cfset arrRow = [] /> <!--- Loop over columns. ---> <cfloop index="strColumn" array="#arrColumns#"> <!--- Add prepared CSV value to row array. ---> <cfset ArrayAppend( arrRow, PrepareCSVValue( qData[ strColumn ][ qData.CurrentRow ] ) ) /> </cfloop> <!--- Now that we have built up our row data, let's collapse it and add it to our master data array. ---> <cfset ArrayAppend( arrData, ArrayToList( arrRow ) ) /> </cfloop> <!--- At this point, we have completely built up our master data array into index-based rows. Now, we have to collapse all those rows down into a single string variable that we can write to the file. ---> <cfset strData = ArrayToList( arrData, (Chr( 13 ) & Chr( 10 )) ) /> <!--- We can now write this data to a file or simply output it. I am outputting for demonstration purposes. ---> <cfoutput> #strData# </cfoutput>