我使用波纹管代码导出gridview数据excel但问题是整个页面导出到excel.我只想要gridview数据而不是整页导出.怎么能解决这个问题? HtmlForm form = new HtmlForm();Response.Clear();Response.Buffer = true;st
HtmlForm form = new HtmlForm(); Response.Clear(); Response.Buffer = true; string filename = "GridViewExport_" + DateTime.Now.ToString() + ".xls"; Response.AddHeader("content-disposition", "attachment;filename=" + filename); Response.Charset = ""; Response.ContentType = "application/vnd.ms-excel"; StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); gdvInBox.AllowPaging = false; gdvInBox.DataBind(); form.Controls.Add(gdvInBox); this.Controls.Add(form); form.RenderControl(hw); //style to format numbers to string string style = @"<style> .textmode { mso-number-format:\@; } </style>"; Response.Write(style); Response.Output.Write(sw.ToString()); Response.Flush(); Response.End();
提前致谢.
设置excel导出非常容易,只导出gridview.这已经过测试,只会导出出现在给定网页上的gridview.对于您的C#代码,请使用以下代码:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class vxcel_export : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button2_Click(object sender, EventArgs e) { Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename=file-name.xls"); Response.ContentType = "application/vnd.xlsx"; System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); GridView1.RenderControl(htmlWrite); Response.Write(stringWrite.ToString()); Response.End(); } public override void VerifyRenderingInServerForm(Control control) { } }
在您的aspx代码中使用以下代码:
确保将EnableEventValidation =“false”添加到<%@ Page%>代码位于页面顶部.
将以下代码放在要将按钮导出gridview到Excel的位置:
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Whatever you want your button to say" />
您可以将高度和宽度修改为按钮中所需的任何大小.
而已.要记住的一件事是,在导出文件时,除非将其另存为工作簿/ Excel文件,否则它不是真正的Excel文件.