[ASP.NET MVC] 匯出 .csv 檔案

常見的匯出檔案有 .pdf .xls .ods .csv,下面筆記最簡單的 .csv 檔,可用常見的 Microsoft Office Excel 或 LibreOffice Calc 等報表軟體開啟: 產生檔案下載 列出清單結果 匯出 .csv 檔案 產生檔案下載 Controller 可以用 return File(); 來做到檔案下載,引數分別為 byte[] 的檔案內容,string 表示的檔案類型和 string 下載後檔案名稱,而 byte[] 類型可用 System.Text.Encoding.Default.GetBytes() 方法來獲得位元組序列,以下為名稱 Demo 的 Controller 程式碼: using System.Text; namespace prjMVC.Controllers { public class DemoController : Controller { public ActionResult GetFiles(string output) { string fileName = "output.txt"; // 存成檔名 byte[] fileContent = Encoding.Default.GetBytes(output); // 轉成位元組序列 return File(fileContent, "text/plain", fileName); } } } 以上 Action 在瀏覽器輸入 ~/Demo/GetFiles?output=xxxx 的網址,或是 View 中有 @Html.ActionLink("下載", "GetFiles", new { output = "xxxx" }) 產生的超連結被點擊時,瀏覽器就會下載一個文字檔案 output.txt: 下面就是傳入 output 字串 "測試文字" 得到的下載文字檔案: 列出清單結果 這個...