Cold Fusion 2018:如何将 .xlsx 文件保存为 .csv

Cold Fusion 2018: how to save .xlsx file as .csv

Win2019上的CF2018 尝试将用户上传的 .xlsx 文件另存为 .csv 文件以处理到 Oracle 数据库中。 运行 此代码完成时没有错误,但结果不清晰:

<cfspreadsheet action = "read"
                format="csv"
                src="c:\bin\Nov_sales.xlsx"
                name="foo"
                > 

<cfspreadsheet action="write" 
                filename='c:\bin\Nov_sales.csv' 
                format="csv" 
                name="foo"  
                overwrite=true>

.csv 文件中的结果如下所示:

504b 0304 1400 0808 0800 d260 8f51 0000
0000 0000 0000 0000 0000 0b00 0000 5f72
656c 732f 2e72 656c 73ad 92c1 4a03 3110
865f 25cc bd9b 6d05 1169 da8b 08bd 89d4
.....

我错过了什么???

“cfspreadsheet 标签始终将电子表格数据写入 XLS 文件。要将 HTML 变量或 CSV 变量写入 HTML 或 CSV 文件,请使用 cffile 标签。”

https://helpx.adobe.com/coldfusion/cfml-reference/coldfusion-tags/tags-r-s/cfspreadsheet.html

或者换句话说,当使用 cfspreadsheet action="write" 时,format 属性不指定输出格式,它指定输入格式 - 因为它可以是 CF 电子表格对象中的任何一个、查询、CSV 字符串或 HTML 字符串。

您在 .csv 文件中看到的是原始字节,因为它实际上是一个 Excel 文件,与 .csv 文件扩展名无关。

假设你的 excel 文件有一个头记录,你应该做的是首先将 excel 文件读入查询对象。从那里,您可以通过使用 <cfoutput> 循环写入文件将查询对象导出到 csv。

<cfspreadsheet action="read" src="c:\bin\Nov_sales.xlsx" query="qryExcel">

<cfoutput query="qryExcel">
    <cfset line = "#col1#,#col2#,#col3#,#col4#,#col5#">
    <cffile action="append" file="c:\bin\Nov_sales.csv" output="#line#">
</cfoutput>

阅读后:

“cfspreadsheet 标签始终将电子表格数据写入 XLS 文件。要将 HTML 变量或 CSV 变量写入 HTML 或 CSV 文件,请使用 cffile 标签。”

我让它工作了,像这样:

<cfquery name="ExportData" datasource="yourdatasource">

    /* Only specify the columns you need to display in the query */

    SELECT *    
    FROM instructor_student_session 

    </cfquery>
<cfset doc_nm = "instructor_student">
<cfscript>
        //Use an absolute path for the files.
        theDir="c:\bin\";
        theXLSXFile="#doc_nm#.xlsx";
        //Create two empty ColdFusion spreadsheet objects.
        theSheet = SpreadsheetNew(true); // creates as xlsx
        //Populate each object with a query.
        //SpreadsheetAddRows(theSheet,ExportData); //no headers
        SpreadsheetAddrows(theSheet,ExportData,1,1,true,[""],true); // add headers
    </cfscript>

<cfset theCSVFile = "#doc_nm#.csv">

<cfspreadsheet action="write" filename="#theDir##theXLSXFile#" name="theSheet" sheetname="Students" overwrite="true">

<cfspreadsheet action = "read" src="#theDir##theXLSXFile#" format="csv" name="csvdata" sheet="1">

<cffile action="write" file="#theDir##theCSVFile#" output="#csvdata#">

<cfheader name="Content-disposition" value="attachment;filename=#theCSVFile#">

<cfcontent type="application/vnd.ms-excel" file="#theDir##theCSVFile#" deletefile="yes">