/// <summary>
/// 将网格数据导出到Excel
/// </summary>
/// <param name="ctrl">网格名称(如GridView1)</param>
/// <param name="FileType">要导出的文件类型(Excel:application/ms-excel)</param>
/// <param name="FileName">要保存的文件名</param>
public void GridViewToExcel(Control ctrl, string FileType, string FileName)
{
bool gridViewAllowPaging = false;
if (ctrl is GridView)
{
gridViewAllowPaging = ((GridView)ctrl).AllowPaging;
if (gridViewAllowPaging)
{
((GridView)ctrl).AllowPaging = false;
}
}
HttpContext.Current.Response.Charset = "GB2312";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;//注意编码
HttpContext.Current.Response.AppendHeader("Content-Disposition",
"attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8).ToString());
HttpContext.Current.Response.ContentType = FileType;//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword
ctrl.Page.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
ctrl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
if (ctrl is GridView && gridViewAllowPaging)
{
((GridView)ctrl).AllowPaging = true;
}
}
行 194: System.IO.StringWriter tw = new System.IO.StringWriter();
行 195: HtmlTextWriter hw = new HtmlTextWriter(tw);
行 196: ctrl.RenderControl(hw);
行 197: HttpContext.Current.Response.Write(tw.ToString());
行 198: HttpContext.Current.Response.End();
|
检查代码,gridView1确实有runat=server标记。此时加入如下代码:
public override void VerifyRenderingInServerForm(Control control) { }
原文地址:http://blog.csdn.net/jumtre/article/details/39313949