導出CSV

public FileResult ExportExcel()
{
var sbHtml = new StringBuilder();
sbHtml.Append("<table border='1' cellspacing='0' cellpadding='0'>");
sbHtml.Append("<tr>");
var lstTitle = new List<string> { "編號", "姓名", "年齡", "建立時間" };
foreach (var item in lstTitle)
{
sbHtml.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item);
}
sbHtml.Append("</tr>");服務器

for (int i = 0; i < 1000; i++)
{
sbHtml.Append("<tr>");
sbHtml.AppendFormat("<td style='font-size: 12px;height:20px;'>{0}</td>", i);
sbHtml.AppendFormat("<td style='font-size: 12px;height:20px;'>屌絲{0}號</td>", i);
sbHtml.AppendFormat("<td style='font-size: 12px;height:20px;'>{0}</td>", new Random().Next(20, 30) + i);
sbHtml.AppendFormat("<td style='font-size: 12px;height:20px;'>{0}</td>", DateTime.Now);
sbHtml.Append("</tr>");
}
sbHtml.Append("</table>");app

//第一種:使用FileContentResult
byte[] fileContents = Encoding.Default.GetBytes(sbHtml.ToString());
return File(fileContents, "application/ms-excel", "fileContents.xls");dom

//第二種:使用FileStreamResult
var fileStream = new MemoryStream(fileContents);
return File(fileStream, "application/ms-excel", "fileStream.xls");ide

//第三種:使用FilePathResult
//服務器上首先必需要有這個Excel文件,然會經過Server.MapPath獲取路徑返回.
var fileName = Server.MapPath("~/Files/fileName.xls");
return File(fileName, "application/ms-excel", "fileName.xls");
}ui

 

 

 

js的代碼:
window.location.href = "Export"; 

後臺代碼:
1
2
3
4
public  FileResult Export()
{
     return  File(Server.MapPath( "/Data/Export.xls" ),  "application/ms-excel" "Export.xls" );
}
相關文章
相關標籤/搜索