I was having one requirement of giving an option to the user to generate the Ms Excel sheet from the report that was given to the user in GridView.
Initially it seems difficult but when I worked around, I found really easy way to do that.
First you need to create a .aspx page where GridView will be placed and data will be rendered.
Here is the code for .aspx page
<asp:GridView ID="GridView1" runat="Server" AutoGenerateColumns="True">
</asp:GridView>
<br />
<asp:Button ID="btn" runat="server" OnClick="GenerateExcelFile" Text="Generate Excel File from GridView" />
Now, We have to write code to populate the GridView, in this example i have used one .xml file to populate the data into the GridView.
.xml file as the datasource of the GridView
<?xml version="1.0" encoding="utf-8" ?>
<GridData>
<Details>
<FirstName>Sheo</FirstName>
<LastName>Narayan</LastName>
<Address>Aurangabad, Bihar</Address>
<Profession>Job</Profession>
</Details>
<Details>
<FirstName>Vijay</FirstName>
<LastName>Bandaru</LastName>
<Address>Hyderabad, AP</Address>
<Profession>Software Professoinal</Profession>
</Details>
<Details>
<FirstName>Sannat</FirstName>
<LastName>Digar</LastName>
<Address>Sanat Nagar, Orrisa</Address>
<Profession>Job</Profession>
</Details>
<Details>
<FirstName>Suraj</FirstName>
<LastName>Singh</LastName>
<Address>Suraj Singh Nagar, Delhi</Address>
<Profession>Businessman</Profession>
</Details>
</GridData>
Now, I am going to write the code to populate the GridView in !
IsPostBack of Page_Load event.
DataSet dSet = new DataSet();
string fileName = Server.MapPath("~/GridData.xml");
dSet.ReadXml(fileName);
GridView1.DataSource = dSet.Tables[0].DefaultView;
GridView1.DataBind();
dSet.Dispose();
Now, I have my GridView populated with the data.
The main part here is to export this GridView as the Ms Excel file, that will be done in the click event of the [Generate Excel File from GridView] button.
To work with following code you may need to add following code at the top of the .cs page.
using System.IO;
using System.Text;
Here is the code for the button click event
string attachment = "attachment; filename=GridViewExport.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sWriter = new StringWriter();
HtmlTextWriter htwWriter = new HtmlTextWriter(sWriter);
GridView1.RenderControl(htwWriter);
Response.Write(sWriter.ToString());
Response.End();
Now you have everything ready to test, but wait. When you click the button you will get error "Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.". To avoid this error, Just add the following method into your .cs file.
public override void VerifyRenderingInServerForm(Control control)
{
}
Now you have everything into your page, go ahead and click the button. It will ask to open or save the Ms Excel file, do whatever you have to do.
Thats it!