Search code examples
excelcoldfusioncoldfusion-10cfspreadsheet

CFspreadsheet looping


I have a question regarding cfspreadsheet....So I'm using cfspreadshseet to create excel spreadsheets for reporting purposes. My page allows a user to select whatever columns from the database to include in the report. So here is an example:

The spreadsheet could look like this:

First Name---Last Name---Organization---Address---City---State---Zip---Concern

Joe Smith Sample 12 main denver co 80513 concerns go here

My question is this, if Joe has more than 1 concern I get multiple rows with joe's info...is there a way I can loop the concerns and only have 1 row for joe?

Thanks,

Steve


Solution

  • Using the "group" feature of cfoutput is perfectly fine for this task. Just to throw out another possibility, you could also generate the list within your database query.

    For example, MySQL has the GROUP_CONCAT function. I do not know the structure of your tables, but say you have two tables User and UserConcern, you could use GROUP_CONCAT like so to concatenate the "Concern" values into a single string:

    SQLFiddle

    SELECT
         u.UserID
         , u.FirstName
         , ... other columns
         , GROUP_CONCAT( uc.Concern ) AS ConcernList
    FROM UserTable u INNER JOIN UserConcern uc
             ON uc.UserID = u.UserID
    GROUP BY 
         u.UserID
         , u.FirstName
         , ... other columns
    

    For SQL Server, a standard trick is to use XML Path:

    SQLFiddle

    SELECT
         u.UserID
         , u.FirstName
         , ... other columns
         , STUFF( ( SELECT ',' + uc.Concern
                    FROM  UserConcern uc
                    WHERE uc.UserID = u.UserID
                    ORDER BY uc.Concern
                    FOR XML PATH('')
                   ) 
                  , 1, 1, ''
              ) AS ConcernList
    FROM UserTable u
    GROUP BY 
         u.UserID
         , u.FirstName
         , ... other columns
    

    Then simply generate your spreadsheet as usual.