Click here to Skip to main content
15,889,992 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I want to make a separate class where i can write a generic method to print or convert any gridview data into excel.

Currently i am able to do it on button click function where i call the my ConvertToExcel method. but i want it to be genric so that i can convert any grid into excel.

Below is my method:

C#
private void Convert_Gridto_Excel(string filename)
        {
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment;filename=" + filename);
            Response.Charset = "";
            // If you want the option to open the Excel file without saving than
            // comment out the line below
            // Response.Cache.SetCacheability(HttpCacheability.NoCache);

            Response.ContentType = "application/vnd.xls";
            System.IO.StringWriter stringWrite = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite =
            new HtmlTextWriter(stringWrite);
            Roster_gridvw.RenderControl(htmlWrite);
            Response.Write(stringWrite.ToString());
            Response.End();
        }
Posted
Updated 15-Oct-13 2:47am
v2
Comments
Simon_Whale 15-Oct-13 6:12am    
why not just pass the gridview control in as an argument.
chandrayog.2 15-Oct-13 6:31am    
please give me an example?

1 solution

C#
public void ConvertToExcel(Datagrid myGrid, string Filename)
{
 //other stuff here
 myGrid.Render(htmlWrite);

 //do other stuff here
}

//you call it by
CovertToExcel(Roster_gridvw, "myfilename.xls");


any problems please let us know and show us what you have done
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900