Export NestedGridView To Excel
In order to export the nested gridview please follow the code below.
SalesReport.Ascx
<%@ Control Language=”C#” AutoEventWireup=”true” Codebehind=”SalesReport.ascx.cs”
Inherits=”Epod.UserControls.SalesReport” %>
<div id=”divgridView” class=”grid”>
<asp:GridView ID=”gvProducts” runat=”server” AllowSorting=”false” AllowPaging=”false” AutoGenerateColumns=”False”
CellPadding=”4″ GridLines=”None” ShowFooter=”false” OnRowCommand=”gvProducts_RowCommand”
Width=”100%”>
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign=”Left”>
<ItemTemplate>
<tr>
<td>
<asp:LinkButton ID=”_btnExpandandCollapse” runat=”server” Text=”<img src=’../images/expand.gif’ alt=’Expand to see detailed report’ border=’0′ />”
CssClass=”GridViewDataHyperLink” CommandArgument=’<%# Container.DataItemIndex %>’
CommandName=’<%# Eval(“ProductId_pk”) %>’ ToolTip=”Expand to see the detailed report”></asp:LinkButton>
<asp:Label ID=”_lblEmployeeName” Font-Bold=”true” runat=”server” Text=’<%# Eval(“ProductName”) %>’></asp:Label>
</td>
</tr>
<tr>
<td colspan=”2″>
<asp:GridView ID=”gvProductOptions” runat=”server” CssClass=”GridView” AllowSorting=”True”
Visible=”false” AutoGenerateColumns=”False” CellPadding=”4″ GridLines=”None”
ShowFooter=”True” AllowPaging=”true” PageSize=”25″ Width=”95%” OnPageIndexChanging=”gvProductOptions_PageIndexChanging”
OnSorting=”gvProductOptions_Sorting”>
<Columns>
<asp:BoundField HeaderText=”Option Title” DataField=”OptionTitle” SortExpression=”OptionTitle”
FooterText=”Total” FooterStyle-Font-Bold=”true” ItemStyle-HorizontalAlign=”Center”/>
<asp:BoundField HeaderText=”Quantity” DataField=”Quantity” SortExpression=”Quantity”/>
<asp:BoundField HeaderText=”Price” DataField=”Price” SortExpression=”Price” ItemStyle-HorizontalAlign=”Center” />
<asp:BoundField HeaderText=”Total Discount” DataField=”TotalDiscount” SortExpression=”TotalDiscount”
ItemStyle-HorizontalAlign=”Center” />
<asp:BoundField HeaderText=”Total BeforeDiscount” DataField=”TotalBeforeDiscount”
SortExpression=”TotalBeforeDiscount” ItemStyle-HorizontalAlign=”Center” />
<asp:TemplateField HeaderText=”Discounted Total” FooterStyle-Font-Bold=”True”>
<ItemTemplate>
<asp:Label ID=”lblDiscountTotal” runat=”server” Text=’<%# GetUnitPrice(DataBinder.Eval(Container.DataItem,”DiscountedTotal”)).ToString(“N2″)%>’></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID=”lblTotal” runat=”server” Text=’<%# GetTotal().ToString(“N2″) %>’></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText=”Organisation Name” DataField=”OrgName” SortExpression=”OrgName”
ItemStyle-HorizontalAlign=”Center” />
</Columns>
<EmptyDataTemplate>
No records available
</EmptyDataTemplate>
<EmptyDataRowStyle CssClass=”EmptyDataRowStyle” />
<FooterStyle CssClass=”FooterStyle” />
<RowStyle CssClass=”RowStyle” />
<EditRowStyle CssClass=”EditRowStyle” />
<SelectedRowStyle CssClass=”SelectedRowStyle” />
<PagerStyle CssClass=”PagerStyle” />
<HeaderStyle CssClass=”HeaderStyle” />
<AlternatingRowStyle CssClass=”AlternatingRowStyle” />
<PagerSettings FirstPageText=”First” LastPageText=”Last” NextPageText=”Next” PreviousPageText=”Previous”
Mode=”NextPreviousFirstLast” />
</asp:GridView>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
No records available
</EmptyDataTemplate>
<EmptyDataRowStyle ForeColor=”black” BackColor=”white” />
</asp:GridView>
</div>
<br />
<p>
<asp:Button ID=”btnExportToExcel” runat=”server” Text=”Export” Visible=”false” OnClick=”btnExportToExcel_Click” />
</p>
<p>
<asp:Label ID=”lblError” runat=”server” CssClass=”ErrorText”></asp:Label>
</p>
Code behind file:
Paste the following code
#region btnExportToExcel_Click Event Start
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
Export(“SalesReport.xls”, gvProducts, “Sales Report”);
}
#endregion btnExportToExcel_Click Event End
#region ExportToExcle Methods Start
public static void Export(string fileName, GridView gv, string title)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader(“content-disposition”, string.Format(“attachment; filename={0}”, fileName));
HttpContext.Current.Response.ContentType = “application/vnd.xls”;
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter htw = new HtmlTextWriter(sw);
try
{
// render the table into the htmlwriter
RenderGrid(gv).RenderControl(htw);
// render the htmlwriter into the response
HttpContext.Current.Response.Write(“” + title + “”);
HttpContext.Current.Response.Write(“<br/><br/>”);
HttpContext.Current.Response.Write(“Report created at: ” + DateTime.Now.ToString());
//HttpContext.Current.Response.Write( System.Web.HttpUtility.HtmlDecode( sw.ToString()));
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
catch (System.Threading.ThreadAbortException lException)
{
// do nothing
}
finally
{
htw.Close();
}
}
}
private static Table RenderGrid(GridView grd)
{
// Create a form to contain the grid
Table table = new Table();
table.GridLines = grd.GridLines;
// add the header row to the table
if (grd.HeaderRow != null)
{
PrepareControlForExport(grd.HeaderRow);
table.Rows.Add(grd.HeaderRow);
}
// add each of the data rows to the table
foreach (GridViewRow row in grd.Rows)
{
//to allign top
row.VerticalAlign = VerticalAlign.Top;
row.HorizontalAlign = HorizontalAlign.Right;
PrepareControlForExport(row);
table.Rows.Add(row);
}
// add the footer row to the table
if (grd.FooterRow != null)
{
grd.FooterRow.HorizontalAlign = HorizontalAlign.Right;
PrepareControlForExport(grd.FooterRow);
table.Rows.Add(grd.FooterRow);
}
return table;
}
private static void PrepareControlForExport(Control control)
{
for (int i = 0; i < control.Controls.Count; i++)
{
Control current = control.Controls[i];
if (current is GridView)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, RenderGrid((GridView)current));
}
if (current is LinkButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl(string.Empty));
}
if (current is Button)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as Button).Text));
}
else if (current is ImageButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
}
else if (current is Label)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as Label).Text));
}
else if (current is HyperLink)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
}
else if (current is DropDownList)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
}
else if (current is CheckBox)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? “Da” : “Nu”));
}
if (current.HasControls())
{
PrepareControlForExport(current);
}
}
}
#endregion ExportToExcle Methods End
This should allow you to export the nested gridview to excel.
Happy coding……………………..
No comments
No comments yet. Be the first.
Leave a reply
