2013-10-21 86 views
0

在我的應用程序中我已經綁定sql數據源到網格視圖,單擊導出按鈕我把數據表中的gridviews數據源並創建webControl表並將該控件寫入xls文件。但我正在逐漸follwowing錯誤:Excel導出不工作與WebControl表

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.

我的代碼如下:

HttpResponse Response = HttpContext.Current.Response; 
Response.Clear(); 
string StudNm = Request["hidStudnm"]; 
Response.AddHeader("content-disposition", "attachment;filename=" + "StudentPasswordReport" + ".xls"); 

Response.Charset = ""; 
Response.ContentType = "application/vnd.xls"; 
System.IO.StringWriter stringWrite = new System.IO.StringWriter(); 
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); 

System.Web.UI.WebControls.Table tblRept; 
tblRept = CreateTable(exportDt); 
tblRept.RenderControl(htmlWrite); 

請告訴我爲什麼發生這個錯誤,我怎麼能甲階酚醛這個錯誤

回答

0

你可以試試這個

DataTableToExcel(exportDt); 

    private void DataTableToExcel(DataTable dataTable) 
    { 
     StringWriter writer = new StringWriter(); 
     HtmlTextWriter htmlWriter = new HtmlTextWriter(writer); 
     GridView gridView = new GridView(); 
     gridView.DataSource = dataTable; 
     gridView.AutoGenerateColumns = true; 
     gridView.DataBind(); 
     gridView.RenderControl(htmlWriter); 
     htmlWriter.Close(); 

     Response.Clear(); 
     Response.AddHeader("content-disposition", "attachment;filename=FileName.xls"); 
     Response.Charset = ""; 
     Response.Write(writer.ToString()); 
     Response.End(); 
} 
相關問題