日期:2014-05-17  浏览次数:20414 次

把GridView中的数据导入excel中,遇到问题
 #region
        protected void GridViewToExcel(GridView Gdv, string stitle)
        {
            try
            {
                Response.Clear();
                Response.Buffer = true;
                Response.Charset = "GB2312";
                string filename = "attachment;filename=" + System.Web.HttpUtility.UrlEncode(stitle, System.Text.Encoding.UTF8) + ".xls";
                Response.AppendHeader("Content-Disposition", filename);
                   Response.ContentEncoding = System.Text.Encoding.UTF7;
                Response.ContentType = "application/ms-excel";
                System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
                System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
                Gdv.AllowPaging = false;
                Gdv.DataBind();
                Gdv.RenderControl(oHtmlTextWriter);
                Response.Output.Write(oStringWriter.ToString());
                Response.Flush();
                Response.End(); 
            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.Message;
            }
        }
        #endregion
运行过程中会有报错(由于代码已经过优化或者本机框架位于调用堆栈之上,无法计算表达式的值),问题应该出在  Response.End()上,但是不用  Response.End()改用HttpContext.Current.ApplicationInstance.CompleteRequest 方法,报错是没有了,但是下载下来的excel不能打开。求高手解决,在上面代码的基础上如何修改!

------解决方案--------------------
亲,试试加上这个吧:
        
public override void VerifyRenderingInServerForm(Control control)
 {
  //no code need
 }