为什么我的Excel导出顶部有一个空白行?
时间:2020-03-06 15:03:19 来源:igfitidea点击:
在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文件会弹出正确的数据。问题在于,Excel文件始终在列标题上方始终以空白的第一行结尾。我只是不知道是什么原因造成的。也许是关于表单标签的事情?也许我需要添加一些样式或者某些东西以去除填充或者边距?我已经尝试了很多方法,但是我无法摆脱那个当当的第一行。还有其他人碰到这个吗?有什么办法吗?
解决方案
这是我的代码,可以正常工作:
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) { }
@azamsharp我在我们回复时在其他地方找到了解决方案。 :-)事实证明,从ASPX页中完全删除form标记是技巧,而唯一的方法是在执行操作时覆盖VerifyRenderingInServerForm方法。
如果我们更新解决方案以包括需要从页面中删除表单标签的事实,我将接受回答。谢谢。
一个更简单的解决方案是重写Render(HtmlTextWriter writer)方法并将其设为空:
受保护的重写void Render(HtmlTextWriter writer){}
http://c-sharpe.blogspot.com/2009/05/get-rid-of-blank-row-when-exporting-to.html