To export data grid view to excel file follow these steps:
- Write a function export( ) as:
private void export(string filename, string type)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=" + filename);
Response.Charset = "";
Response.ContentType = type;
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.RenderControl(hw); //render the gridview
Response.Output.Write(sw.ToString());
Response.Flush();
Response.Close();
Response.End();
}
here name of our grid view is GridView1 so we have used GridView1.RenderControl(hw);
here name of our grid view is GridView1 so we have used GridView1.RenderControl(hw);
- Write public override void and select VerifyRenderingInServerForm(Control control) from intelisense, function will displayed as:
public override void VerifyRenderingInServerForm(Control control)
{
base.VerifyRenderingInServerForm(control);
}
Now comment the line in function as:
public override void VerifyRenderingInServerForm(Control control)
{
// base.VerifyRenderingInServerForm(control);
}
We have done this for rendering of data grid view
- Now call the function export( ) on button_click( ) as:
export("myfile.xls","application/vnd.ms-excel");
the file will be saved as myfile.xls you can specify other name for file also.
for exporting to .xlsx file use "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" instead of "application/vnd.ms-excel" and change the file extension as "myfile.xlsx"
the file will be saved as myfile.xls you can specify other name for file also.
for exporting to .xlsx file use "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" instead of "application/vnd.ms-excel" and change the file extension as "myfile.xlsx"
No comments:
Post a Comment