Export data table to Excel Sheet(CSV) on Button Click

First You have to Create a grid view that will show details which you want to Export

<asp:GridView ID=”GridView1″ CssClass=”footable” runat=”server” AutoGenerateColumns=”false”
        Style=”max-width: 500px” >
        <Columns>
            <asp:BoundField DataField=”Id” HeaderText=”Id” />
            <asp:BoundField DataField=”Name” HeaderText=”Name” />
            <asp:BoundField DataField=”Company” HeaderText=”Company” />
            <asp:BoundField DataField=”Age” HeaderText=”Age” />
        </Columns>
    </asp:GridView>

Bind you details to GridView
C# Code Behind:-
public static DataTable dt; //Declare your dt globle to paas it in another function
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
dt = new DataTable();
dt.Columns.AddRange(new DataColumn[4] { new DataColumn(“Id”), new DataColumn(“Name”), new DataColumn(“Company”), new DataColumn(“Age”) });
dt.Rows.Add(1, “Savan”, “MSOSL”, 23);
dt.Rows.Add(2, “Rupesh”, “KLOSJ”, 25);
dt.Rows.Add(3, “Rahul”, “JSKL”, 26);
GridView1.DataSource = dt;
GridView1.DataBind();
}

}

Create a button that will export you details to Excel

<asp:Button ID=”Button1″ runat=”server” Text=”Export” OnClick=”Button1_Click”  />

Call the function on click event
C# Code Behind:-

protected void Button1_Click(object sender, EventArgs e)
{
ExportDataTableToCSV(dt);

}

protected void ExportDataTableToCSV(DataTable dt)
{

Response.Clear();
Response.ContentType = “text/csv”;
Response.AddHeader(“content-disposition”, “attachment;filename=Customers.csv”);

StringBuilder sb = new StringBuilder();

for (int i = 0; i < dt.Columns.Count; i++)
{
sb.Append(dt.Columns[i].ColumnName + ‘,’);
}
sb.Append(Environment.NewLine);

for (int j = 0; j < dt.Rows.Count; j++)
{
for (int k = 0; k < dt.Columns.Count; k++)
{
sb.Append(dt.Rows[j][k].ToString() + ‘,’);
}
sb.Append(Environment.NewLine);
}
Response.Write(sb.ToString());
Response.End();
}

Screenshot

CSV

NGenious Solutions