Вы находитесь на странице: 1из 5

Export to Excel

including styles
ASP.NET
2

Default.aspx

I have added one gridview and a link button for exporting to


excel.

<table class="tblStyle">
<tr>
<td align="right">
<asp:LinkButton ID="LinkButton1" runat="server"
Text="Export to Excel" OnClick="LinkButton1_Click"></asp:LinkButton>
</td>
</tr>
</table>
<asp:Panel ID="pnlUsers" runat="server">
<table class="tblStyle">
<tr>
<td align="center">
<asp:Label ID="lblheader" runat="server"
Text="User Details" CssClass="pageHeader"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="grvTest" runat="server"
AutoGenerateColumns="false">
<HeaderStyle CssClass="gridHeader" />
<RowStyle CssClass="gridItem" />
<Columns>
<asp:BoundField HeaderText="ID"
DataField="id" HeaderStyle-CssClass="idStyle" />
<asp:BoundField HeaderText="Name"
DataField="name" HeaderStyle-CssClass="nameStyle" />
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</asp:Panel>

Now if you are using update panel in your page and click on
export button you’ll get an error similar to the following
3

To avoid this error include the post back trigger for the link
button.
<Triggers>
<asp:PostBackTrigger ControlID="LinkButton1" /> </Triggers>

Other solution is to put your link button outside upadte


panel.

Now after including the postbacktrigger when you click on


export you’ll get another runtime error(saying control must be
placed inside a form tag with runat=server) similar to the
following

To avoid this error in your code behind(Default.aspx.cs)


inlcude the folloiwng function
public override void VerifyRenderingInServerForm(Control control)
{
return;
4

Now to preserve CSS Styles in your Ecel also use the folloiwng Export
functions

public void Export(Control control)


{
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);

// prepare control for export


PrepareControlForExport(control);

// render the cpntrol into the htmlwriter


control.RenderControl(htw);
Export(sw.ToString());
}

public void Export(string htmlContent)


{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader(
"content-disposition", string.Format("attachment;
filename={0}", this.FileName));
HttpContext.Current.Response.ContentType = "application/vnd.ms-
excel";
HttpContext.Current.Response.Charset = "utf-8";

string strHtml = string.Empty;


string path =
HttpContext.Current.Server.MapPath("~\\Styles\\StyleSheet.css");
string cssSheet = System.IO.File.ReadAllText(path);

strHtml += "<html><head>";
strHtml += "<style type=\"text/css\">";
strHtml += cssSheet;
strHtml += "</style></head><body>";

strHtml += "<table style=\"width: 100%\"><tr><td>";


strHtml += htmlContent + "</td></tr></table>";
strHtml += "</body></html>";

// render the htmlwriter into the response


HttpContext.Current.Response.Write(strHtml);
HttpContext.Current.ApplicationInstance.CompleteRequest();
}

Results
5

Вам также может понравиться