导出到Excel错误

我试图通过popup导出一个数据网格到Excel。 我能够从我的应用程序中删除代码时成功导出到Excel,但是,当试图使用我的应用程序中完全相同的代码导出到Excel时,我收到以下错误:

从我的try / catch:

无法评估expression式,因为代码已经过优化,或者本地框架位于调用堆栈之上。

…从控制台:

错误:Sys.WebForms.PageRequestManagerParserErrorException:从服务器收到的消息无法parsing。

我的服务器端代码如下所示:

protected void btnExportToExcel_Click(object sender, EventArgs e) { ExportDataSetToExcel(); } private void ExportDataSetToExcel() { try { DataTable dt = new DataTable("GridView_Data"); foreach (TableCell cell in gvPatientRoster.HeaderRow.Cells) { dt.Columns.Add(cell.Text); } foreach (GridViewRow row in gvPatientRoster.Rows) { dt.Rows.Add(); for (int i = 0; i < row.Cells.Count; i++) { dt.Rows[dt.Rows.Count - 1][i] = row.Cells[i].Text; } } if (dt != null && dt.Rows.Count > 0) { Response.ContentType = "application/vnd.ms-excel"; Response.AppendHeader("Content-Disposition", string.Format("attachment; filename=PatientRoster.xls")); System.IO.StringWriter tw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); DataGrid dgGrid = new DataGrid(); dgGrid.DataSource = dt; //Report Header hw.WriteLine("<b><u><font size='5'>" + "Patient Roster</font></u></b>"); hw.WriteLine("<br><br>"); //hw.Write(BuildCriteriaString()); hw.WriteLine("<br>"); // Get the HTML for the control. dgGrid.HeaderStyle.Font.Bold = true; dgGrid.DataBind(); dgGrid.RenderControl(hw); // Write the HTML back to the browser. this.EnableViewState = false; Response.Write(tw.ToString()); Response.End(); } } catch (Exception ex) { lblErrorMessage.Text = ex.Message; } } 

我在PageLoad()中添加了以下内容,导出工作正常:

 ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page); scriptManager.RegisterPostBackControl(this.btnExportToExcel); 

它看起来像UpdatePanelScriptManager是我忽略的元素。 当我从主应用程序分离function时,我没有包含主应用程序中的所有HTML。 由于ScriptManagerUpdatePanel不是孤立function的一部分,因此它可以正常工作。 我一定会在下次发布HTML

这是来自以下post的解决scheme:

Sys.WebForms.PageRequestManagerParserErrorException:从服务器收到的消息无法parsing

我会build议使用其中一个很好,免费的C#“导出到Excel”库。

您已经编写了将数据读取到DataTable的代码,一旦使用了这种格式,就可以使用以下免费的C#库…

ExportToExcel库

…你将能够将数据导出到一个“真正”的Excel 2007文件中的一行代码….

 // Export the DataTable into an Excel file, and write it to the web Response CreateExcelFile.CreateExcelDocument(dt, "SomeFilename.xlsx", Response); 

好吧,好吧,两行代码。 我添加了一条评论。

但是你明白了!