Controller Methods:
public ActionResult TitlesList()
{
return View(db.Titles.ToList());
}
public void ExportToExcel()
{
string Filename = "Titles.xls";
string FolderPath = HttpContext.Server.MapPath("/ExcelFiles/");
string FilePath = System.IO.Path.Combine(FolderPath, Filename);
//Step-1: Check if file name exists in server then remove from server.
if (System.IO.File.Exists(FilePath))
{
System.IO.File.Delete(FilePath);
}
//Step-2: Get Html Data & Converted to String
List titlesList = db.Titles.OrderBy(d => d.TitleID).ToList();
string HtmlResult = RenderRazorViewToString("TitlesList", titlesList);
//Step-3: Html Result store in Byte[] array
byte[] ExcelBytes = System.Text.Encoding.ASCII.GetBytes(HtmlResult);
//Step-4: byte[] array converted to file Stream and save in Server
using (Stream file = System.IO.File.OpenWrite(FilePath))
{
file.Write(ExcelBytes, 0, ExcelBytes.Length);
}
//Step-5: Download Excel file
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(Filename));
Response.WriteFile(FilePath);
Response.End();
Response.Flush();
}
//end of Controller Methods