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)
{
}
}
Originally Posted on September 25, 2013
Last Updated on October 26, 2015
Last Updated on October 26, 2015
All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.