在我的应用程序中我将sql数据源绑定到网格视图,单击导出按钮我在datatable中获取了gridviews数据源并创建了webControl表并将该控件写入xls文件。但是我得到了以下错误:
无法评估表达式,因为代码已优化或本机框位于调用堆栈之上。
我的代码如下:
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 :(得分: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();
}