2LeggedSpider

Creating a Word document using ASP.NET and C#

Posted in ASP.NET, C# by Sumit Thomas on June 30, 2004

In one of my projects recently, I had to create word documents dynamically using ASP.NET. I turned to MSDN for help and was surprised to find how easy it was to do so.

I am using Visual Studio 2002 and .NET Framework 1.0. Therefore if you are using the latest versions, unlike me :-( then do check out for the updates in the classes and methods that I am going to use in this article.

1) OK, lets start. Open up Visual Studio and create an ASP.NET Web application using C#.

2) Now we have to add a COM reference to our project. In the references dialog box, under COM you will find Microsoft Word 9.0 Object Library. Select it and add it to the project. This will add few COM dll’s in the bin directory.

3) Now the code…

object fileName="D:\\MyWord.doc";
object novalue=System.Reflection.Missing.Value;

Word.ApplicationClass objWord = new Word.ApplicationClass();
Word.Document objWordDoc=objWord.Documents.Add(ref novalue, ref novalue, ref novalue, ref novalue);

objWordDoc.Activate();

objWord.Selection.TypeText(".NET Rocks!!!");
objWord.Selection.TypeParagraph();
objWord.Selection.TypeText("Savage loves .NET");

objWordDoc.SaveAs(ref fileName, ref novalue, ref novalue, ref novalue,
            ref novalue, ref novalue, ref novalue, ref novalue, ref novalue,
            ref novalue, ref novalue); 

objWord.Quit(ref novalue, ref novalue, ref novalue);

Now check the MyWord.doc file in the D: drive.

The code is pretty simple and intuitive, hence a quick explanation.

* We are first creating a object of Word.ApplicationClass
* Next we add a Word document to this object. Incase you don’t want to pass a particular parameter, use the ‘novalue’ object that we have created in the code.
* The following steps are pretty self explanatory.

The Visual Studios’ Intellisense feature will let us know of the expected parameters of each method. In the latest versions of .NET framework the number of parameters required is more.

Do check out http://msdn.microsoft.comto learn about automation in .NET

Technorati: , ,
About these ads
Tagged with: , , , ,

38 Responses

Subscribe to comments with RSS.

  1. Voniak said, on September 9, 2007 at 10:17 am

    Hi,

    I tried this with updated classes from VS 2005 and Word 12.0

    My intention was to implement simple functionality to save search results page as a word document.

    However solution propsed here has one big problem:

    Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80070005.

    After a research I found out that it’s because MS Word wasn;t designed as a server-side application so an local account on server machine WITH appropriate priviledges is required (to set up impersonating in .NET application). However, such a setup can be a serious security issue, so I abandoned this attempt.

    is there anyone who tried this solution and it worked for him (without impersonation setup etc.)?

    • MJT said, on July 24, 2009 at 7:45 pm

      Don’t use impersonation.

      1. On 2003 server, create a COM+ component in VB.Net or similar. Run this under the local account, and set up a dummy Service under the same account to make sure that the user profile is loaded. Always run Word up interactive under the account when setting up to initialise the user settings.

      2. On 2008 server, launch Word via the application pool account e.g. do a RevertToSelf. Make sure the pool has “Load User Profile” ticked in its Advanced Settings

  2. 2leggedspider said, on September 14, 2007 at 8:55 am

    Office applications were never intended for server side use and therefore dont take in to consideration the security issues involved in a distributed environment. Though we can perform automation as mentioned in the post with the necessary security adjustments, it is NOT recommended for live public websites. Perhaps for intranets you might want to try it.

    More information on this would be highly appreciated.

  3. Harold said, on March 4, 2008 at 7:53 pm

    Wow. Thanks for this. Very informative. We just signed up with Server Intellect for our Windows web hosting and have never been more pleased — they are one of the first to uprade as a Microsoft Gold Certified Partner – to Windows Server 2008 ‘Longhorn’ on all Dedicated Servers – and it includes many upgrades and additions, like new web, security and virtualization technologies.

  4. Yogananda said, on April 8, 2008 at 11:26 am

    it is ultimate concept

  5. smsMantra.blogspot.com said, on May 5, 2008 at 1:13 pm

    thanks

  6. mindgrillq.blogspot.com said, on May 6, 2008 at 11:05 am

    great one

  7. Kasper said, on August 6, 2008 at 11:40 pm

    OH My!!! .. thanx for this post.

  8. Vitalii said, on December 23, 2008 at 1:43 am

    try Invoke lib for creating docx files http://invoke.co.nz/products/help/docx.aspx

  9. Zakaria said, on January 18, 2009 at 5:03 am

    hi…..
    this is great sln….
    but i can not run it from server….
    how coul i run….
    anyone give me the sln…or how to configure the server for create the doc file…

  10. lexx said, on June 29, 2009 at 5:54 pm

    How can i change font size and color?

  11. aaaa ssssssss ddd said, on August 21, 2009 at 9:13 am

    sdf

  12. Bhalchandra said, on October 18, 2009 at 12:59 pm

    Hi,

    Gr8 sln. Thnx a lot.

  13. Memory card said, on May 26, 2010 at 7:59 pm

    This post gave us an important Brainstorm session of all the options we could make use of on our blog.

  14. rlejason said, on August 4, 2010 at 11:31 am

    I suggest to use a .net word component, I use it long time, quit good.
    http://www.e-iceblue.com/Introduce/word-for-net-introduce.html

  15. Delbert Espenscheid said, on December 31, 2010 at 5:33 am

    Great article. There’s a lot of nice information. I did want to let you know something though – I am running Redhat with the latest of Firefox and the layout of your blog is kind of bizarre for me. I can understand the articles, but the navigation doesn’t function so great.

  16. Rajesh Singh said, on February 25, 2012 at 5:18 pm

    Very nice article. I really enjoyed it reading. And it also cleared lot of my doubts about Creating doc file using c# code. Check this link too its also explain very well.

    http://www.mindstick.com/Articles/956444a2-60c9-4d34-bb73-8c27039379d7/?HOW%20TO%20CREATE%20DOC%20FILE%20INSIDE%20FOLDER

    Thanks Everyone!!

  17. ru said, on April 12, 2013 at 10:39 pm

    I like the valuable information you provide in your articles.
    I’ll bookmark your blog and check again here regularly. I’m quite certain I will learn many new stuff right here!
    Best of luck for the next!

  18. golf tips said, on June 22, 2013 at 5:27 am

    definitely much like your site nevertheless you need to take a look at the transliteration for a number of your posts. A number of these are filled using punctuational problems we to uncover this quite irritating in all seriousness however I’m going to absolutely can come all over again once again.

  19. It’s a shame you don’t have a donate button! I’d definitely donate to this superb blog! I suppose for now i’ll settle for book-marking and adding your RSS feed to my Google account.
    I look forward to fresh updates and will share this site with my Facebook
    group. Chat soon!

  20. Juli said, on February 10, 2014 at 9:07 am

    If some one wishes to be updated with most recent technologies afterward
    he must be go to see this site and be up to date
    everyday.

  21. sandra said, on February 12, 2014 at 8:42 am

    This solution is not recommended, especially for server side. We now have Open XML SDK which is a much tedious approach compared to Office COM (Word Automation), but it doesn’t require MS Word (installed on a production machine).
    And if you need a Mail-Merge solution (populating templates with data) then take a look at this product:
    http://www.docentric.com
    It only requires several lines of code and templates can be created in Word.

    • Herc said, on February 12, 2014 at 9:00 am

      Open XML SDK is only a practical solution for building fairly simple documents from scratch. For anything else, such as editing existing documents, it is not just tedious as nigh impossible. It does not provide a mechanism for document format conversion either, and the Office Automation Services are equally impractical – poor functionality and lock-in to SharePoint. Frankly, server-side automation remains a better solution than anything Microsoft has provided since.

      We have moved from server-side Office automation for complex document editing and format conversion to using the Aspose toolset. It has a few issues, but much better anything else I have seen, good support too.

  22. how to download project spark beta said, on February 15, 2014 at 10:17 am

    As the admin of this website is working, no doubt very rapidly it will be famous, due to
    its feature contents.

  23. Walter said, on February 22, 2014 at 8:28 am

    What’s Happening i’m new to this, I stumbled upon this I’ve discovered It absolutely useful and it has aided me out loads.

    I hope to contribute & help other customers like its helped me.
    Good job.

  24. redsocial.sexmart.com.mx said, on February 26, 2014 at 1:46 pm

    Ahaa, its fastidious dialogue concerning this post here at this blog,
    I have read all that, so now me also commenting here.

  25. thatgrapejuice.net said, on March 1, 2014 at 9:27 pm

    A few years ago, one of our local residents, Mac
    Vorce, who is also a bicycle enthusiast petitioned for the
    development of bicycle paths and trails. No matter what your field, it helps to know what you’re good at, but
    it also helps to recognize what others are good at.

    Brad Garret is a stand-up comedian but also well known for his acting career.

  26. quintalstore.com.br said, on March 8, 2014 at 1:23 pm

    After I originally left a comment I seem to have clicked the
    -Notify me when new comments are added- checkbox and now whenever a comment is added I recieve four
    emails with the exact same comment. There has to be a means you are able to
    remove me from that service? Kudos!

  27. Very soon this website will be famous amid all blogging users, due to it’s pleasant content

  28. http://www.julian-kuiters.id.au/ said, on March 13, 2014 at 7:44 am

    Hi, just wanted to say, I liked this blog post. It was helpful.
    Keep on posting!

  29. Dwain said, on March 13, 2014 at 8:42 am

    Hello to all, it’s genuinely a good for me to pay a visit this web site, it contains
    valuable Information.

  30. www.mainstreetroswell.org said, on March 15, 2014 at 10:11 pm

    Great post. I was checking continuously this blog and I am impressed!

    Extremely useful info specially the last part :) I care for such information much.
    I was looking for this certain info for a long time.
    Thank you and best of luck.

  31. Genf20 scam said, on March 31, 2014 at 5:29 am

    Some of such benefits are: increased secretion of HGH,
    raises the connection between other hormones, enhancing the synthesis
    of Phosphatidyl Choline to improve mental focus and cognition function, improves is a result of workouts, improves
    fat removal from the liver to help prevent obesity and diabetes, and decreases the likelihood of heart attack, stroke and Alzheimer’s disease.
    These are all the natural link between aging, which is simply because your body slows
    producing HGH or human growth hormones. A lot in the brands available
    in the market are simply regular multi vitamin pills that are packaged
    as human growth hormones supplements.

  32. http://www.androidosfan.com/ said, on April 2, 2014 at 11:14 am

    Here are the unique features of the incredible phone:. Overall, analysts were all
    products of the “evolution” of upgrades and features lighter and thinner left a deep impression.
    It’s also done on cameras, however superior lenses generally larger storage means an electronic camera will be the
    better option.

  33. DB Vehicle Electrics said, on April 16, 2014 at 6:44 am

    Hi superb blog! Does running a blog like this require a lot of work?
    I have virtually no expertise in programming however I had been hoping to start my
    own blog soon. Anyway, should you have any suggestions or tips
    for new blog owners please share. I know this is off subject nevertheless I just had to ask.
    Many thanks!

  34. letter pictures art said, on April 16, 2014 at 9:02 am

    Right now??

  35. Autumn said, on April 17, 2014 at 4:28 am

    Humans evolved this ability as a way to compel us to complete the things that make us feel great – like eating and having
    sex. This can bring about blood clots if fat or cholesterol are let go in the circulatory system.
    When you judge yourself for any failure, you create an emptiness inside that then really wants
    to get filled.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: