Introducing DotNetFunda.com on mobile http://m.dotnetfunda.com ! Be with DotNetFunda.com on the go !
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 5867 |  Welcome, Guest!   Register  Login
Home > Articles > ASP.NET > Generating Ms Word document in ASP.NET and C#

Generating Ms Word document in ASP.NET and C#

3 vote(s)
Rating: 4.33 out of 5
Article posted by Raja on 9/11/2007 | Views: 46119 | Category: ASP.NET | Level: Intermediate red flag


It is very frequntly asked question in any of the forum or question-answer section on websites. So I decided to write a very compact article with source code.

It is as simple as 123.

Download


 Download source code for Generating Ms Word document in ASP.NET and C#




Lets start with creating a simple .aspx page where we will give a text box to enter user's Name and a button to click on. After clicking on the button Ms Word document will be generated.

.aspx page

The code will be
<form id="form1" runat="server">

<div>
Write your name: <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator id="req1" runat="server" ControlToValidate="txtName" Text="*"></asp:RequiredFieldValidator>
<br />
<asp:Button ID="btn" runat="server" OnClick="GenerateMsWordDoc" Text="Generate Ms Word Document" />
</div>
</form>


When button will be clicked, GenerateMsWordDoc event will fire.

Now lets write the code behind code. What we are going to do here is we are generating a dynamic html content based on the textbox value. Also we are writing one table with 2 cell and at last we are adding some text.

.cs file code


protected void GenerateMsWordDoc(object sender, EventArgs e)

{
string strBody = "<html>" +
"<body>" +
"<div>Your name is: <b>" + txtName.Text + "</b></div>" +
"<table width="100%" style="background-color:#cfcfcf;"><tr><td>1st Cell body data</td><td>2nd cell body data</td></tr></table>" +
"Ms Word document generated successfully." +
"</body>" +
"</html>";
string fileName = "MsWordSample.doc";
// You can add whatever you want to add as the HTML and it will be generated as Ms Word docs
Response.AppendHeader("Content-Type", "application/msword");
Response.AppendHeader ("Content-disposition", "attachment; filename="+ fileName);
Response.Write(strBody);
}


Thats we have to do!!!.

Just download the sample code and start using it.

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

About Raja Dutta

Experience:5 year(s)
Home page:http://www.dotnetfunda.com
Member since:Monday, June 02, 2008
Level:Starter
Status: [Member]
Biography:
 Responses
Posted by: Poster | Posted on: 16 Oct 2008 10:15:38 AM

Really simple.

Thanks Raja.

Posted by: Spentsarsky | Posted on: 01 Feb 2009 08:53:06 PM

Here is the component that generates document based on the custom template. The documents are generated from the sharepoint list ... so the data is pulled from the list item into the document on the fly:
http://store.sharemuch.com/products/generate-word-documents-from-sharepoint-list

Hope that helps,

Yaroslav Pentsarskyy
Blog: www.sharemuch.com

Posted by: Seenuvasan | Posted on: 10 Jun 2011 09:20:57 AM | Points: 25

hi..
how to give name for this word document. because i think ,it's shows class name as filename .

Posted by: Teshow | Posted on: 26 Sep 2011 05:50:04 AM | Points: 25

Useful. Also, I want to show my C# code for generating Word document.

Document doc = new Document();

//Create a new secition
Section section = doc.AddSection();

//Create a new paragraph
Paragraph paragraph = section.AddParagraph();

//Append Text
paragraph.AppendText("E-Iceblue,hello");


I use a component Spire.Doc(Download here:http://www.e-iceblue.com/Download/download-word-for-net-now.html), which helps me generate Word more easily.

Posted by: Mickwen0k | Posted on: 19 Oct 2011 04:43:57 AM | Points: 25

Spire.Doc work quite well, I use it from last year. that's great!

Posted by: Kukurice | Posted on: 29 Dec 2011 04:48:37 AM | Points: 25

Hi!

Generating Microsoft Word documents using HTML is a far better approach than the Office COM (MS Office automation) one. This solution is robust but is probably limited in terms of charts, pictures, and all other MS Word concepts that are at least hard to achieve. This was a MS Word document generation solution for some quite time in our company, then we purchase Docentric toolkit (http://www.docentric.com) which pushed our previous solution into oblivion. It really helped at building templates and also ther maintinance is much better (customers frequently want to change copany logo in header, add a data field, ...). Before choosing the product we tested couple of other commercial products and docentric proved far better, simply for the following reasons: document templates and a very powerfull Word add-in.

>> Write Response - Respond to this post and get points
Related Posts

If you want to modify some functionality of existing Grid View control of ASP .Net then you always have the option of extending the control. In this article I have extend the Grid View with custom field. To extend the Grid View control you can inherit the new class from existing class or any of the following class 1). DataControlField – The base class for bind field 2). ButtonFieldBase – The base class for all button field and command field. In this article I am extending the Grid View control of ASP .Net with LongTextField and ConfirmDeleteButton (it will be in my next blog)

Many times we want to implement pre-processing logic before a request hits the IIS resources. For instance you would like to apply security mechanism, URL rewriting, filter something in the request etc. ASP.NET has provided two types of interception HttpModule and HttpHandler. This article walks through it.

This article will help us to implement resizable gridview column There's four important points to remember about it all. 1.Based on how the code is written, the Grid that has resizable columns must be contained in some other element (in these examples I use a DIV) and that element must have a style set of "position: absolute;". You need this to size the black vertical bar that attaches to the mouse correctly when performing an actual resize. 2.Based on how the code is written, you can only perform resize operations on table header cells (TH tags). This simply feels like the right way to do it - you could make it TD tags instead, and be able resize the column for the entire height of the table if you wanted to. 3.The actual table must have a style set of "table-layout: fixed;" If you don't set this style, strange things happen (try it and see, it goes all loopy when you resize . 4.To save having to remember to put too many requirements in the implementation, the black vertical bar is created dynamically. It's important to leave the creation of this element until the page's onload event fires - if it runs before it finishes loading, you IE sometime throws an error trying to call document.body.appendChild() - it took us ages to debug this!

To pass value from one page to another page using querystring and accessing that value to retrieve database information, we can follow this approach.

To render a TextBox,DropDownList , ListBox as a mandatory field for the end user to input data before a form can be submitted to the server, we can follow this approach.

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you found plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/21/2012 8:08:56 AM