为什么我的Excel导出在顶部有一个空行?

在ASP.NET中,我通过将DataSet绑定到GridView然后将ContentType设置为Excel来将一些数据导出到Excel。

我的ASPX页面非常简单,如下所示:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ExamExportReport.aspx.cs" Inherits="Cabi.CamCentral.Web.Pages.Utility.ExamExportReport" %> <html> <body> <form id="form1" runat="server"> <asp:GridView ID="gridExam" AutoGenerateColumns="true" runat="server"> </asp:GridView> </form> </body> </html> 

在后面的代码的Page_Load方法中,我正在这样做:

 protected void Page_Load(object sender, EventArgs e) { BindGrid(); Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("content-disposition", "attachment; filename=ExamExport.xls"); } 

一般来说,一切正常,Excel文件popup正确的数据。 问题在于,Excel文件总是以列头之上的空白第一行结束。 我只是无法弄清楚是什么原因造成的。 也许这是关于窗体标签的东西? 也许我需要添加一些样式或东西去除填充或边距? 我尝试了一堆东西,但我不能摆脱那第一个空白行。 有没有其他人遇到这个? 任何解决scheme

@azamsharp – 当你回答时,我在别处find了解决办法。 :-)事实certificate,从ASPX页面中完全删除表单标签是绝招,唯一的办法就是重写VerifyRenderingInServerForm方法。

如果您更新您的解决scheme,以包括您需要从页面中删除表单标签的事实,我会接受您的答案。 谢谢。

这是我的代码工作正常:

 protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { BindData(); } } private void BindData() { string connectionString = "Server=localhost;Database=Northwind;Trusted_Connection=true"; SqlConnection myConnection = new SqlConnection(connectionString); SqlDataAdapter ad = new SqlDataAdapter("select * from products", myConnection); DataSet ds = new DataSet(); ad.Fill(ds); gvProducts.DataSource = ds; gvProducts.DataBind(); } protected void ExportGridView(object sender, EventArgs e) { Response.ClearContent(); Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls"); Response.ContentType = "application/excel"; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); gvProducts.RenderControl(htw); Response.Write(sw.ToString()); Response.End(); } public override void VerifyRenderingInServerForm(Control control) { } 

更简单的解决scheme是重写Render(HtmlTextWriter作家)方法并将其设置为空:

保护覆盖无效渲染(HtmlTextWriter作家){}

http://c-sharpe.blogspot.com/2009/05/get-rid-of-blank-row-when-exporting-to.html