Related Tags:
Asp.Net It was developed by Microsoft to allow programmers to build dynamic web sites, web applications and web services. It was first released in January 2002 with version 1.0 of the .NET Framework, and is the successor to Microsoft's Active Server Pages (ASP) technology. Learn More, C# C# (pronounced "C-sharp") is an object-oriented programming language from Microsoft that aims to combine the computing power of C++ with the programming ease of Visual Basic. C# is based on C++ and contains features similar to those of Java. Learn More, ASP.NET MVC The ASP.NET MVC framework is a lightweight, highly testable presentation framework that (as with Web Forms-based applications) is integrated with existing ASP.NET features, such as master pages and membership-based authentication. The MVC framework is defined in the System.Web.Mvc assembly. Learn More,

How to export my object to excel file and download the file as well ?

Description:I want my class object directly export to a excel file and force download the file as well using C# code. A generic method or code chunk would be more appreciated in which i can send any object to be exported to excel file.

Posted by: | Posted on: Oct 03, 2017

1 answers

Replies

2

For converting the List of objects of your class in a excel file and to make it forcefully download as well, you need to create following methods

   
public void ExportToExcel(object items)
{
System.Web.UI.WebControls.DataGrid grid = new System.Web.UI.WebControls.DataGrid();
grid.HeaderStyle.Font.Bold = true;
grid.DataSource = items;
grid.DataBind();
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
grid.RenderControl(hw);
SendFileToBrowser(sw,"MyFileName");
}

public void SendFileToBrowser(StringWriter stringWriter, string fileName)
{
string attachment = "attachment;filename=" + fileName + ".xls";
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "application/ms-excel";
//following two lines to support languages other than english as well.
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble());
HttpContext.Current.Response.Write(stringWriter.ToString());
HttpContext.Current.Response.End();
}


For using the above code you can just simply call the "ExportToExcel" method with providing your list as shown below

List<MyClass> listOfMyClass = new List<MyClass>();
//Fill the data from your data source
//Call the following method
ExportToExcel(listOfMyClass);

Replied by: | Replied on: Oct 04, 2017



Reply
×

Code block Hyperlink bold Quotes block Upload Images

Preview