Add GridView, Datasource, and Button
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="exporttest.aspx.cs" EnableEventValidation="false" Inherits="ExportTest" %> <form id="form1" runat="server"> <asp:gridview runat="server" id="gvExport" allowpaging="True" autogeneratecolumns="False" datakeynames="id" datasourceid="dsExport"> </asp:gridview> <asp:sqldatasource id="dsExport" runat="server" conflictdetection="CompareAllValues" connectionstring="<%$ ConnectionStrings:DbConnection %>" selectcommand="SELECT top 100 * FROM Users"> </asp:sqldatasource> <asp:button id="btnExport" runat="server" onclick="Button1_Click" text="Export To Excel" /> </form>
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class ExportTest : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { Response.Clear(); gvExport.AllowPaging = false; gvExport.DataBind(); Response.AddHeader("content-disposition", "attachment;filename=FileName.xls"); Response.ContentType = "application/vnd.xls"; System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); gvExport.RenderControl(htmlWrite); Response.Write(stringWrite.ToString()); Response.End(); } public override void VerifyRenderingInServerForm(Control control) { } }
Last Updated on October 26, 2015