CSV or Excel file download in asp.net


Many systems have requirement to download the file in different format like Excel, CSV, etc. For that we are using HttpContext.Current.Response class in System.Web namespace.

Following is the code to download the CSV file:

try

{

HttpContext.Current.Response.Clear();

HttpContext.Current.Response.ClearHeaders();

HttpContext.Current.Response.ClearContent();

HttpContext.Current.Response.AddHeader(“content-disposition”, “attachment; filename = FileName.csv”);

HttpContext.Current.Response.ContentType = “text/csv”;

HttpContext.Current.Response.AddHeader(“Pragma”, “public”);

Response.WriteFile(Server.MapPath(“~/ExcelFiles/FileName.csv”));

HttpContext.Current.Response.End();

Response.Flush();

}

catch (Exception ex)

{

throw ex;

}
We can download the excel file by just changing the HttpContext.Current.Response.ContentType to Application/x-msexcel.

Advertisements