coldfusioncoldfusion-11cfspreadsheet

How to loop through cfspreadsheet headers?


I have an excel file that I am trying to read and then display the values of the headers in a drop down. The first row in my excel file has all of the values (header names).

I used the code below, but what happens is that all the header names appear in a single line with commas. I want the headers to be separated, so that it will appear in the drop down with many <option>, instead of a single <option>. How do I do that?

    <!-- Read the header values from excel -->
    <cfset spreadsheet = "uploads/spreadsheet.xlsx">

    <cfspreadsheet action="read" headerrow="1" src="uploads/spreadsheet.xlsx" query="excelHeader" rows="1" />

    <cfset excelHeaders = excelHeader.columnList>

    <!-- Display the header names as a dropdown -->
    <select name="id_headers">
        <option>
            #excelHeaders#
        </option>
    </select>

Solution

  • You can try this code;

    <!--- create new spreadsheet and populate with sample data --->
    <cfset theSheet = SpreadsheetNew("Expenses")>
    <cfset SpreadsheetSetCellValue(theSheet,"column1",1,1)> 
    <cfset SpreadsheetSetCellValue(theSheet,"column2",1,2)>
    <cfset SpreadsheetSetCellValue(theSheet,"column3",1,3)>
    <cfset SpreadsheetSetCellValue(theSheet,"column4",1,4)>
    
    <!--- Write the spreadsheet to a file, replacing any existing file. ---> 
    <cfset pathToFile = GetDirectoryFromPath(GetCurrentTemplatePath()) & "newSpreadsheet.xls">
    <cfspreadsheet action="write" filename="#pathToFile#" name="theSheet" overwrite=true>
    
    <!--- Read spreadsheet into query object ---> 
    <cfspreadsheet action="read" headerrow="1" src="#pathToFile#" query="excelHeader" rows="1">
    
    <!--- Display the header names as a dropdown --->
    <cfoutput>
    <select name="id_headers">
    <cfloop list="#excelHeader.columnList#" index="option">
        <option>#option#</option>
    </cfloop>
    </select>
    </cfoutput>
    

    You can run this code snippet in trycf