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.doc","application/msword");
the file will be saved as myfile.doc you can specify other name for file also.
for exporting to .docx file use "application/vnd.openxmlformats-officedocument.wordprocessingml.document" instead of "application/msword" and change the file extension as "myfile.docx"
the file will be saved as myfile.doc you can specify other name for file also.
for exporting to .docx file use "application/vnd.openxmlformats-officedocument.wordprocessingml.document" instead of "application/msword" and change the file extension as "myfile.docx"
No comments:
Post a Comment