如何将GridView中的数据保存到Excel
下面是我使用的方法:
#region 导出为Excel
public override void VerifyRenderingInServerForm(Control control)
{
// 这个方法一定要写,不能省略
}
private void toExcelClk() //单击引出按钮调用的方法
{
this.GridView1.AllowPaging = false;//在开始导出前,要禁止分页,以保让所有的数据都被导出
this.GridView1.AllowSorting = false;
showData();读取数据到gridview
ToExcel(this.GridView1, "OFS_Data.xls");//调用导出方法
GridView1.AllowPaging = true; //导出完成后,重新设置允许分页和排序
GridView1.AllowSorting = true;
showData();重新读取数据到gridview
}
private void ToExcel(Control ctl, string FileName)
{
HttpContext.Current.Response.Charset = "utf-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + FileName);
ctl.Page.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}
#endregion
public override void VerifyRenderingInServerForm(Control control)
{
// 这个方法一定要写,不能省略
}
private void toExcelClk() //单击引出按钮调用的方法
{
this.GridView1.AllowPaging = false;//在开始导出前,要禁止分页,以保让所有的数据都被导出
this.GridView1.AllowSorting = false;
showData();读取数据到gridview
ToExcel(this.GridView1, "OFS_Data.xls");//调用导出方法
GridView1.AllowPaging = true; //导出完成后,重新设置允许分页和排序
GridView1.AllowSorting = true;
showData();重新读取数据到gridview
}
private void ToExcel(Control ctl, string FileName)
{
HttpContext.Current.Response.Charset = "utf-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + FileName);
ctl.Page.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}
#endregion