In this asp.net tutorial you will learn how to export div data to excel. Sometime we may have got requirement to export the div data to excel and this tutorial is written for fulfilling that purpose. You can export data that lie within table, paragraphs etc to excel. In this tutorial i have put table inside the div and then export that div. Now let's have a look over how to do so
Export div data to excel in asp.net using
Export_div_data.aspx<form id="form1" runat="server"> <div id="divExport" runat="server"> <table width="500" border="1" cellspacing="0" cellpadding="0"> <tr> <td align="left" valign="top" bgcolor="#FFECF5"><strong>id</strong></td> <td align="left" valign="top" bgcolor="#FFECF5"><strong>Name</strong></td> <td align="left" valign="top" bgcolor="#FFECF5"><strong>Birth Date</strong></td> <td align="left" valign="top" bgcolor="#FFECF5"><strong>Gender</strong></td> </tr> <tr> <td align="left" valign="top">1</td> <td align="left" valign="top">Haris Fakhar</td> <td align="left" valign="top">15/10/1984</td> <td align="left" valign="top">male </td> </tr> <tr> <td align="left" valign="top">2</td> <td align="left" valign="top">Omer Fakhar</td> <td align="left" valign="top">01/09/1986</td> <td align="left" valign="top">male</td> </tr> </table> </div> </form> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Export to Excel" />
Simply in .aspx page we have a div, I give id to the div and also used its runat="server" attribute so that div can be accessed from server side, inside div we have a table that data will be exported to excel.
Export_div_data.aspx.cs
using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Net; using System.IO;//Donot forget to import this namespace protected void Button1_Click(object sender, EventArgs e) { Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename=FileName.xls"); Response.Charset = ""; Response.ContentType = "application/vnd.xls"; System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); divExport.RenderControl(htmlWrite); Response.Write(stringWrite.ToString()); Response.End(); }This code is quite simple, I m adding header for .xls file and then using StringWriter and HtmlTextWriter class I am exporting div data into excel.
Happy Coding!!!