In this tutorial you will learn how to export div data into ms word in asp.net using c#. Sometime we may have got requirement to export the div data into ms word and this tutorial is written for fulfilling that purpose. You can export data that lie within table, paragraphs etc to word. In this tutorial i have put table inside the div and then export it. Now let's have a look over how to do so
Export div data to ms word in asp.net using c#
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 Word" />
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 word.
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.doc"); Response.Charset = ""; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = "application/doc"; 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(); }
The only difference between export div to excel and export div to word is that while exporting div data to word we are setting the SetCacheability to NoCache.
Happy Coding!!!