用的是Html拼接成Table表格的方式,返回
FileResult 輸出一個二進制的文件.
第一種:使用FileContentResult
//
// 摘要: // 通過使用文件內容,內容類型,文件名稱創建一個FileContentResult對象// // 參數: // fileContents: // 響應的二進制文件內容 // // contentType: // 內容類型(MIME類型) // // fileDownloadName: // 顯示在瀏覽器下載窗口的文件名稱// // 返回結果: // 文件內容對象. protected internal virtual FileContentResult File(byte[] fileContents, string contentType, string fileDownloadName);
需要將文件內容轉化成字節數組byte[]
byte[] fileContents = Encoding.Default.GetBytes(sbHtml.ToString());
第二種:使用FileStreamResult
// 其他參數描述同FileContentResult
// 參數: // fileStream: // 響應的流 // // 返回結果: // 文件流對象. protected internal virtual FileStreamResult File(Stream fileStream, string contentType, string fileDownloadName);
需要將文件內容轉化成流
var fileStream = new MemoryStream(fileContents);
第三種:使用FilePathResult
// 其他參數描述同FileContentResult
// 參數: // fileName: // 響應的文件路徑 // // 返回結果: // 文件流對象. protected internal virtual FilePathResult File(string fileName, string contentType, string fileDownloadName);
服務器上首先必須要有這個Excel文件,然會通過Server.MapPath獲取路徑返回.
具體詳情請看代碼.

1 public FileResult ExportExcel() 2 { 3 var sbHtml = new StringBuilder(); 4 sbHtml.Append("<table border='1' cellspacing='0' cellpadding='0'>"); 5 sbHtml.Append("<tr>"); 6 var lstTitle = new List<string> { "編號", "姓名", "年齡", "創建時間" }; 7 foreach (var item in lstTitle) 8 { 9 sbHtml.AppendFormat("<td style='font-size: 14px;text-align:center; font-weight:bold;' height='25'>{0}</td>", item); 10 } 11 sbHtml.Append("</tr>"); 12 13 for (int i = 0; i < 1000; i++) 14 { 15 sbHtml.Append("<tr>"); 16 sbHtml.AppendFormat("<td style='font-size: 12px;height:20px;'>{0}</td>", i); 17 sbHtml.AppendFormat("<td style='font-size: 12px;height:20px;'>屌絲{0}號</td>", i); 18 sbHtml.AppendFormat("<td style='font-size: 12px;height:20px;'>{0}</td>", new Random().Next(20, 30) + i); 19 sbHtml.AppendFormat("<td style='font-size: 12px;height:20px;'>{0}</td>", DateTime.Now); 20 sbHtml.Append("</tr>"); 21 } 22 sbHtml.Append("</table>"); 23 24 //第一種:使用FileContentResult 25 byte[] fileContents = Encoding.Default.GetBytes(sbHtml.ToString()); 26 return File(fileContents, "application/ms-excel", "fileContents.xls"); 27 28 //第二種:使用FileStreamResult 29 var fileStream = new MemoryStream(fileContents); 30 return File(fileStream, "application/ms-excel", "fileStream.xls"); 31 32 //第三種:使用FilePathResult 33 //服務器上首先必須要有這個Excel文件,然會通過Server.MapPath獲取路徑返回. 34 var fileName = Server.MapPath("~/Files/fileName.xls"); 35 return File(fileName, "application/ms-excel", "fileName.xls"); 36 }