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

One Response to CSV or Excel file download in asp.net

  1. The least expected conclusion. But when you think about, diversity in thought is good for the community as a whole.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: