使用coldfusion將HTML表格輸出成EXCEL檔案(使用者下載)

Coldfusion 的檔案輸出控制,主要有下面兩個指令
<cfcontent><cfheader>
cfcontent 用來告訴瀏覽器等一下要輸出的內容是甚麼格式
cfheader 用來宣告傳輸資料的相關資訊

簡單的輸出測試  saveFileTest.cfm:
<cfsetting enablecfoutputonly="Yes">
<cfcontent type=
"application/vnd.ms-excel; charset=big5">
<cfheader name=
"Content-Disposition" value="attachment;filename=ODR10001234567.xls">
<!--- office Excel Format Structure--->
<cfoutput><html xmlns:x="urn:schemas-microsoft-com:office:excel">
<head>
<meta http-equiv=
"Content-Type" content="text/html;charset=big5">
<!--[if gte mso 9]>
<xml>
<x:ExcelWorkbook>
<x:ExcelWorksheets>
<x:ExcelWorksheet>

<!--- this line names the worksheet --->
<x:Name>訂單狀態</x:Name>
<x:WorksheetOptions>

<!--- these 2 lines are what works the magic --->
<x:Panes>
</x:Panes>
</x:WorksheetOptions>
</x:ExcelWorksheet>
</x:ExcelWorksheets>
</x:ExcelWorkbook>
</xml>
<![endif]-->

</head>
<body>

<table border="0" cellpadding="1" cellspacing="2">
<tr>
<th>
客戶編號</th><th>業務員</th><th>出貨員</th><th>訂單日</th><th>訂單號</th><th>訂購人</th><th>批號</th><th>交付日</th><th>交付時間</th><th>應收款</th><th>實收款</th><th>交易狀況</th></tr>
<tr>
<td style=
'vnd.ms-excel.numberformat:@'>00987</td>
<td>
苗小平</td>
<td>
江企財</td>
<td>
2013/05/30</td>
<td style=
'vnd.ms-excel.numberformat:@'>BCDF9876534</td>
<td>
黃疆普</td>
<td style=
'vnd.ms-excel.numberformat:@'>0098765432</td>
<td>
2013/06/25</td>
<td>
11:30</td>
<td>
1200</td>
<td>
1200</td>
<td>
100-success</td>
</tr>
<tr>
<td style=
'vnd.ms-excel.numberformat:@'>00147</td>
<td>
林英蠻</td>
<td>
江企財</td>
<td>
2013/05/30</td>
<td style=
'vnd.ms-excel.numberformat:@'>BCDF98788471</td>
<td>
劉力行</td>
<td style=
'vnd.ms-excel.numberformat:@'>0098765431</td>
<td>
2013/07/01</td>
<td>
13:00</td>
<td>
8477.5</td>
<td>
8477</td>
<td>
50-discount</td>
</tr>
</table>

</body>
</html>

</cfoutput>


首先,使用 cfsetting enablecfoutputonly="Yes" 來壓制不必要的空白輸出,
然後,cfcontent type="application/vnd.ms-excel; charset=big5"
宣告文件為excel類型,且為big5編碼,
接著,cfheader name="Content-Disposition" value="attachment;filename=ODR10001234567.xls"
告訴瀏覽器,這是附件下載的檔案 ODR10001234567.xls
接著用 cfoutput 輸出內容,簡易的excel內容編制可以使用HTML格式,但是需要經過宣告

最開始的 html 到 body 這一段就是讓excel認識下面的html table屬於excel內容編排
中間的<table></table>就是內容編排,你會發現它就是很標準的HTML table 表

注意的是有個 style='vnd.ms-excel.numberformat:@' 宣告,這是讓excel不要過度雞婆把『疑似數字』的內容自動轉成數字,因為會很捆擾的,比竟某些場合的數字是當成字串使用,因為excel轉數字的話會把前面的 0 自動取消掉。

執行這個網頁會直接讓瀏覽器輸出存檔,檔案名稱就是 ODR10001234567.xls(當然儲存時可以改)

如何?簡單吧...

留言

這個網誌中的熱門文章

【研究】列印的條碼為什麼很難刷(掃描)

C# 使用 Process.Start 執行外部程式

統一發票列印小程式