Ashok N

Ashok N

  • NA
  • 8
  • 8.8k

ExportToExcel functionality in a Class file

Aug 13 2010 9:11 AM
Hi,

When I call the below function in ButtonDownLoad_Click like:- ExportToExcel(gv) ,I'm able to export the GridView contents to an xls file.

Please refer attached 
ExportToExcel.rar

But there so many aspx pages with GridViews which I need to export to excel.

So I tried to keep the above export-coding in a Class as below

public class Class1 : System.Web.UI.Page

{
public void ExportToExcel(GridView Gv)

{

Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
//this.ClearControls(Gv);
Gv.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}

}


protected void ButtonDownLoad_Click(object sender, EventArgs e)
{
// ExportToExcel(gv); // function call within same page works fine..
Class1 c1 = new Class1();
c1.ExportToExcel(gv);
}

After Button click ,Getting error as below...

"Response is not available in this context."

Please suggest the solution so that above class can be used in all the pages (to avoid keeping code in every page).


Thanks in advance...

Attachment: ExportToExcel.rar

Answers (1)