Skip to main content

Dynamic Generation of Word Document Report in ASP.NET with HTML


Overview
Ever needed to generate Word documents from your ASP.NET applications? There are a couple of components which will help to generate Word documents, but using these components may have some overhead such as Component Registration, setting permissions, licenses, etc., Sometimes, it may even become difficult to understand their features and use them. Generating word document in ASP.NET with HTML is incredibly easy.
The following sample demonstrates how to place Heading and Table dynamically in the word document in ASP.NET web applications using HTML.
Requirements
Microsoft Visual Web Developer 2005 Express Edition
Create the Web Application project
Add the new Web Site Application project (with name as Generate Word Document) and place the button (with name as btnGenerateDocument) in the Default.aspx web form as shown below.

Double click the highlighted code behind file from the Solution Explorer and add the following namespaces.
Listing 1
using System;
using System.Data;
using System.Configuration;
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;
Finally, paste the following code in the button click event
Listing 2
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset ="";
 
HttpContext.Current.Response.ContentType ="application/msword";
 
string strFileName = "GenerateDocument"+ ".doc";
HttpContext.Current.Response.AddHeader("Content-Disposition",
  "inline;filename=" + strFileName);
 
StringBuilder strHTMLContent = newStringBuilder();
 
strHTMLContent.Append(
  " <h1 title='Heading' align='Center'style='font-family: verdana; font -size: 80 % ;
 color: black'><u>Document Heading</u> <  / h1 > ".ToString());
 
strHTMLContent.Append("<br>".ToString()); strHTMLContent.Append(
  "<table align='Center'>".ToString());
 
// Row with Column headers
strHTMLContent.Append("<tr>".ToString()); strHTMLContent.Append(
  "<td style='width:100px; background:
# 99CC00'><b>Column
1 <  / b >  <  / td >".ToString());
 
strHTMLContent.Append("<td style='width:100px;background:
# 99CC00'><b>Column
2 <  / b >  <  / td >".ToString());
 
strHTMLContent.Append("<tdstyle='width:100px; background:
# 99CC00'><b>Column 3</b>
 <  / td >".ToString());strHTMLContent.Append(" <  / tr > ".ToString());
 
// First Row Data
strHTMLContent.Append("<tr>".ToString()); strHTMLContent.Append(
  "<td style='width:100px'>a</td>" .ToString()); strHTMLContent.Append(
  "<td style='width:100px'>b</td>" .ToString()); strHTMLContent.Append(
  "<td style='width:100px'>c</td>" .ToString());strHTMLContent.Append("</tr>"
  .ToString());
 
// Second Row Data
strHTMLContent.Append("<tr>".ToString()); strHTMLContent.Append(
  "<td style='width:100px'>d</td>" .ToString()); strHTMLContent.Append(
  "<td style='width:100px'>e</td>" .ToString()); strHTMLContent.Append(
  "<td style='width:100px'>f</td>" .ToString()); strHTMLContent.Append("</tr>"
  .ToString());
 
strHTMLContent.Append("</table>".ToString());
 
strHTMLContent.Append("<br><br>".ToString()); strHTMLContent.Append(
  "<p align='Center'> Note : This is adynamically generated word document  <  / p > ".ToString());
HttpContext.Current.Response.Write(strHTMLContent);
HttpContext.Current.Response.End();
HttpContext.Current.Response.Flush();
In the above listing, first the Response object is cleared, charset is set to empty and then Content type is set to MS Word.
Filename is defined for the document which will be generated through this code and this is set to the "Content-Disposition" header of the Response object.
Now to the StringBuilder variable -- it is an HTML representation of the heading and table with three columns and two rows along with column headers and data appended. This content will be displayed in the Word document when it is generated.
Once the contents to be displayed in the document are set, the Response object’s Write, End and Flush methods send the output to the browser, where the user's copy of Microsoft Word will open the content and render it as a Word document.
Run the Web Application
Once the application is run, the following screen is displayed in the browser.

Click the Generate Document button in the above screen upon which the following prompt will be displayed to open or save the document. 

Comments

Popular posts from this blog

GRIDVIEW GROUPING

When displaying data, we sometimes would like to group data for better user experience or when displaying long list of hierarchal data, we would want to display them in a tree view kind of structure. There is more than way of doing this, but I am going to explain achieving this functionality using  AJAX Collapsible Panel Extender Control . Overview: I am going to use  Adventure Works  as datasource. Every product in  Production.Product  table belongs to a product sub category. We fetch handful of products and the sub categories they belong to from the database. Our objective is to list all the available sub categories and allow user to  expand/collapse  to look/hide the list of products belonging to each subcategory. Database Connection Added following entry under  connectionStrings  element in  web.config . < add   name = "Sql"   connectionString="Data Source=(local); Initial  Catalog = AdventureWorks ...

GRIDVIEW ZOOM IMAGE

When you have images in your  GridView , you would most likely show them as thumbnails so as to not distort the whole layout. However user would want to look at the full image by clicking on the image or just hovering his mouse over it. In today’s applications, this is a basic requirement and there are just so many third party controls or plugins which would support this functionality. I am going do this conventional way using  javascript  way in this article.  On top of it, I am also going to explain how to get images from database using  HttpHandlers . Example: I am using  Adventure Works  as datasource. We fetch handful of products and bind them to the grid. When page is initially loaded, we retrieve products from Production . Product  table and bind them to the grid. We display some product attributes such as Product ID, Product Number, Product Name, List Price and product’s thumbnail. When user hover his mouse on the page, we fetch the f...

Editing Child GridView in Nested GridView

Editing Child GridView in Nested GridView In this article we will explore how to edit child gridview in the nested gridview.   Let''s write some code. Step 1:  Add scriptmanager in the aspx page. < asp : ScriptManager   ID ="ScriptManager1"   runat ="server"   EnablePageMethods ="true"> </ asp : ScriptManager > Step 2:  Add below stylesheet for modal popup. < style   type ="text/css">        .modalBackground        {              background-color : Gray;              filter : alpha(opacity=80);              opacity : 0.5;       }        .ModalWindow        {     ...