Visual Studio .NET - gridview export to excel sheet with multiple tabs

Asked By Partha Mandayam on 26-Mar-08 06:52 PM
I have a gridview which shows details of different products. I want to export it to an excel spreadsheet which has different tabs for each product details. How can I do this?

` Export to Excel - with worksheets

mv ark replied to Partha Mandayam on 26-Mar-08 07:05 PM
Check this article "Can I Get That As a Spreadsheet?" - http://www.15seconds.com/issue/031007.htm ,  for ideas

It utilizes MS Office HTML/XML & it is a pretty lightweight option.

Use this Sample code

Tushar Dabhi replied to Partha Mandayam on 26-Mar-08 07:39 PM

ExcelExport.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExportExcel.aspx.cs" Inherits="DeleteConfirm" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Contacts Listing</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<strong><span style="font-size: small; font-family: Arial; text-decoration: underline">

Contacts Listing

    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Export To Excel" /></span></strong><br />

<br />

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ContactID"

DataSourceID="SqlDataSource1" EmptyDataText="There are no data records to display." style="font-size: small; font-family: Arial" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Vertical">

<Columns>

<asp:BoundField DataField="ContactID" HeaderText="ContactID" ReadOnly="True" SortExpression="ContactID" Visible="False" />

<asp:BoundField DataField="FName" HeaderText="First Name" SortExpression="FName" />

<asp:BoundField DataField="LName" HeaderText="Last Name" SortExpression="LName" />

<asp:BoundField DataField="ContactPhone" HeaderText="Phone" SortExpression="ContactPhone" />

<asp:TemplateField HeaderText="Favorites">

<ItemTemplate>

     

    <asp:CheckBox ID="CheckBox1" runat="server" />

</ItemTemplate></asp:TemplateField>

</Columns>

<FooterStyle BackColor="#CCCC99" />

<RowStyle BackColor="#F7F7DE" />

<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />

<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />

<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />

<AlternatingRowStyle BackColor="White" />

</asp:GridView>

 

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ContactsConnectionString1 %>"

DeleteCommand="DELETE FROM [ContactPhone] WHERE [ContactID] = @ContactID" InsertCommand="INSERT INTO [ContactPhone] ([FName], [LName], [ContactPhone]) VALUES (@FName, @LName, @ContactPhone)"

ProviderName="<%$ ConnectionStrings:ContactsConnectionString1.ProviderName %>"

SelectCommand="SELECT [ContactID], [FName], [LName], [ContactPhone] FROM [ContactPhone]"

UpdateCommand="UPDATE [ContactPhone] SET [FName] = @FName, [LName] = @LName, [ContactPhone] = @ContactPhone WHERE [ContactID] = @ContactID">

<InsertParameters>

<asp:Parameter Name="FName" Type="String" />

<asp:Parameter Name="LName" Type="String" />

<asp:Parameter Name="ContactPhone" Type="String" />

</InsertParameters>

<UpdateParameters>

<asp:Parameter Name="FName" Type="String" />

<asp:Parameter Name="LName" Type="String" />

<asp:Parameter Name="ContactPhone" Type="String" />

<asp:Parameter Name="ContactID" Type="Int32" />

</UpdateParameters>

<DeleteParameters>

<asp:Parameter Name="ContactID" Type="Int32" />

</DeleteParameters>

</asp:SqlDataSource>

 

<br />

</div>

</form>

</body>

</html>

ExcelExport.aspx.cs 

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Text;

using System.IO;

 

public partial class DeleteConfirm : System.Web.UI.Page

{

 

    protected void Page_Load(object sender, EventArgs e)

    {

    }

 

    protected void Button1_Click(object sender, EventArgs e)

    {

        //Export the GridView to Excel

        PrepareGridViewForExport(GridView1);

        ExportGridView();

    }

 

    private void ExportGridView()

    {

        string attachment = "attachment; filename=Contacts.xls";

        Response.ClearContent();

        Response.AddHeader("content-disposition", attachment);

        Response.ContentType = "application/ms-excel";

        StringWriter sw = new StringWriter();

        HtmlTextWriter htw = new HtmlTextWriter(sw);

        GridView1.RenderControl(htw);

        Response.Write(sw.ToString());

        Response.End();

    }

 

    public override void VerifyRenderingInServerForm(Control control)

    {

    }

 

    private void PrepareGridViewForExport(Control gv)

    {

        LinkButton lb = new LinkButton();

        Literal l = new Literal();

        string name = String.Empty;

        for (int i = 0; i < gv.Controls.Count; i++)

        {

            if (gv.Controls[i].GetType() == typeof(LinkButton))

            {

                l.Text = (gv.Controls[i] as LinkButton).Text;

                gv.Controls.Remove(gv.Controls[i]);

                gv.Controls.AddAt(i, l);

            }

            else if (gv.Controls[i].GetType() == typeof(DropDownList))

            {

                l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;

                gv.Controls.Remove(gv.Controls[i]);

                gv.Controls.AddAt(i, l);

            }

            else if (gv.Controls[i].GetType() == typeof(CheckBox))

            {

                l.Text = (gv.Controls[i] as CheckBox).Checked ? "True" : "False";

                gv.Controls.Remove(gv.Controls[i]);

                gv.Controls.AddAt(i, l);

            }

            if (gv.Controls[i].HasControls())

            {

                PrepareGridViewForExport(gv.Controls[i]);

            }

        }

    }

}

 

*********************

If the above ExportGridView function gives erroe then use following function.

********************

private void ExportGridView()

{

          string attachment = "attachment; filename=Contacts.xls";

          Response.ClearContent();

          Response.AddHeader("content-disposition", attachment);

          Response.ContentType = "application/ms-excel";

          StringWriter sw = new StringWriter();

          HtmlTextWriter htw = new HtmlTextWriter(sw);

 

          // Create a form to contain the grid

          HtmlForm frm = new HtmlForm();

          GridView1.Parent.Controls.Add(frm);

          frm.Attributes["runat"] = "server";

          frm.Controls.Add(GridView1);

 

          frm.RenderControl(htw);

          //GridView1.RenderControl(htw);

          Response.Write(sw.ToString());

          Response.End();

}

gridview

sundar k replied to Partha Mandayam on 27-Mar-08 12:06 AM

I dont think using Gridview.rendercontrol you can export your resultsets into multiple sheets, as it by default writes the data into a single sheet, but you can show link buttons in excel sheet which can paginate the records, but still if you want data in multiple sheets grouped by product, then you will have write custom code to loop through the dataset and export the data into various sheets for each product.

If you want to implement paging in exporting data to excel, you can check out the below link
http://www.gridviewguy.com/ArticleDetails.aspx?articleID=197

you can find lot of code snippets in google for exporting dataset(in your case you can frame a select which can group by product and if the proudct value changes you can write the datatable content to another new sheet) to different excel sheets of excel file, one of which is as below,

Export data to multiple sheets of Excel doc

http://www.c-sharpcorner.com/Blogs/BlogDetail.aspx?BlogId=283

m
Mani Muthu replied to Partha Mandayam on 29-Apr-08 02:49 AM
end of post
gridview
Partha Mandayam replied to sundar k on 30-Apr-08 01:44 PM
These articles still don't describe exporting a gridview directly to an excel sheet with multiple tabs. Doing 1 tab is easy - how to do multiple tabs?