Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » VB.NET » Creating and opening Microsoft Word document

Creating and opening Microsoft Word document


This article is being written in response to a couple inquiries on the question, "How do I open a word document from .NET?".

Author Rank:
Total page views :  70210
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor

Figure 1 - Word Launched from .NET Form.

This article is being written in response to a couple inquiries on the question, "How do I open a word document from .NET?".    I guess after people read my excel article, they were under the impression that I knew how to do this in Word.  Luckily, after some hunting around on the forums and feedback from other VB.NET Corner members I got the gist of it.

The First Step in manipulating Word in .NET is that you'll need to add a COM reference to your project by right clicking in the solution explorer on References->Add Reference.  Click on the COM tab and look for the Microsoft Word 9.0 Object Library.  Click Select and OK.


This will automatically place an assembly in your application directory that wraps COM access to Word.  Now we are ready to create a word object in our code.  To instantiate an instance of a Word application, you just declare the line below in your class:

Private WordApp As New Word.ApplicationClass.

Now you can call the interesting methods and properties that Microsoft Word provides to you to manipulate documents in Word.  Personally, I never want to figure the Microsoft Word code out myself, because the Word hierarchy and properties, although rich in features, has a bit of a learning curve.  So in order to jump straight over the learning curve,  I simple turn the Macro Recorder on in Word and let Word write the code for me.  (Of course this is VBA code, but...close enough).  To start the macro recorder in Word, go to  Tools->Macro->Record New Macro inside Microsoft Word.  Now anything you type, open, delete, or format, will get recorded in VBA, so you have a clue how to write your Word Interoperability code.

The application in this particular article is divided into two methods based on the button that is pressed in the form.  The first  button opens an existing Word Document and adds a copyright line to the document.  The second button creates a new document, and brings up a dialog to allow you to enter a title to the document.

Below is the code for the first button event handler:

Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
' Use the open file dialog to choose a word document
If Me.openFileDialog1.ShowDialog() = DialogResult.OK Then
' set the file name from the open file dialog
Dim fileName As Object = openFileDialog1.FileName
Dim [readOnly] As Object = False
Dim isVisible As Object = True
' Here is the way to handle parameters you don't care about in .NET
Dim missing As Object = System.Reflection.Missing.Value
' Make word visible, so you can see what's happening
WordApp.Visible = True
' Open the document that was chosen by the dialog
Dim aDoc As Word.Document = WordApp.Documents.Open(fileName, missing,
[readOnly], missing, missing, missing, missing, missing, missing, missing, missing, isVisible)
' Activate the document so it shows up in front
aDoc.Activate()
' Add the copyright text and a line break
WordApp.Selection.TypeText("Copyright C# Corner")
WordApp.Selection.TypeParagraph()
End If
End
Sub 'button1_Click

The code above opens a document based on the file chosen in the OpenFileDialog.  Notice the parameters passed to the Document.Open method are all references.  Don't ask me why it was done this way, but it seems like when Microsoft goes through a call with optional parameters, they had no choice but to make everything a variant so on the VB.NET side of  the parameter list  looks like a bunch of references to objects.  If you want to skip over a parameter in the call to Open, use the System.Reflection.Missing.Value and assign it to an object.  Once you know this trick, the rest of the interoperability used with Word is pretty straightforward.

Below is the code for creating a document from scratch:

Private Sub button2_Click(ByVal sender As Object, ByVal e As System.EventArgs)
' Use the custom dialog to get the title of the document from the user
Dim theQueryDialog As New TitleQuery
If theQueryDialog.ShowDialog() = DialogResult.OK Then
' vba code generated from recorded macro to "remind me" how to do it.
'
***************************************************************
' Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter
' Selection.Font.Bold = wdToggle
' Selection.TypeText Text:="Creating a Title"
' Documents.Add Template:="C:\My Documents\CSharp Book Project\Normal.dot", _
' NewTemplate:=False, DocumentType:=0
'
***************************************************************
' Set up all the parameters as generic objects so we can pass them in
documents.Add
Dim missing As Object = System.Reflection.Missing.Value
Dim fileName As Object = "normal.dot" ' template file name
Dim newTemplate As Object = False
Dim docType As Object = 0
Dim isVisible As Object = True
' Create a new Document, by calling the Add function in the Documents collection
Dim aDoc As Word.Document = WordApp.Documents.Add(fileName, newTemplate, docType, isVisible)
' need to see the created document, so make it visible
WordApp.Visible = True
aDoc.Activate()
' Global Constant enumerations are members of Word and can be assigned to properties
' Set alignment to the center of the document
WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter
' Toggle the title to a Bold Font
WordApp.Selection.Font.Bold = CInt(Word.WdConstants.wdToggle)
End If ' Type the Text of the Title that was inputted by the user in the Custom Dialog WordApp.Selection.TypeText(theQueryDialog.Title);
End Sub 'button2_Click

The code above is a little less intuitive, so I used the Macro Recorder in VBA to spit out the VBA code for creating a document.  Creating a document is done through the Documents Collection.  The Add method of the Documents Collection creates a new document and brings it up in Word.  The Add method allows you to specify the template to use and the document type.  Note that the Add method also takes optional parameters, so as a result, you need to pass it a series of references to objects  that box the types you would normally pass. 

The title being placed in the document is formatted using some of the existing Word global enumeration constants.  These constants tend to be constants nested in constants for organizational purposes.  Although VBA gives you a clue to the relative name of the constants, you need to hunt for them a little bit using intellisense to find the parent enumeration.  The code above uses the global enumerations to first center the title and then make it bold.  The final line is similar to the previous listing in that it types the title into the Document.

Conclusion.

I hope this article gives you a head start in controlling word from .NET and VB.NET.  It's a little more cumbersome than VBA but it's much less cumbersome than Visual C++ and MFC.  Remember to take advantage of the Microsoft Word Macro Recorder to help you along (this helpful hint also applies to coding in excel and other Microsoft products).  Hopefully with a little coding and the power of .NET Rapid Application Development, you can add some very powerful reporting features to your applications that incorporate Microsoft Word.


Login to add your contents and source code to this article
 About the author
 
Mike Gold
Michael Gold is President of Microgold Software Inc., makers of the WithClass UML Tool. His company is a Microsoft VBA Partner and Borland Partner. Mike is a Microsoft MVP and founding member of C# Corner. He has a BSEE and MEng EE from Cornell University and has consulted for Chase Manhattan Bank, JP Morgan, Merrill Lynch, and Charles Schwab. Currently he is a senior developer at Finisar Corp. He has been involved in several .NET book projects, and is currently working on a book for using .NET with embedded systems. He can be reached at mike@c-sharpcorner.com
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
ASP.Net 4 Hosting is here
Become a Sponsor
 Comments
lies by white On May 8, 2007
you have taught me a lesson never to tell the truth a gain
Reply | Email | Delete | Modify | 
Re: lies by Mike On May 9, 2007

huh?  no idea why you made this statement, but you might start by spelling again (your spelling a gain)

a-g-a-i-n

Reply | Email | Delete | Modify | 
Cannot Open Word Document at Client Side by saraswathi On April 29, 2009
The above code works fine at server side. But, at client side, the MS word object is initialised but nothing is happening as I can find winword.exe in the Task Manager Hope can get reply from you.... Thanks in advance
Reply | Email | Delete | Modify | 
The RPC server is unavailable. (Exception from HRESULT: 0x800706BA) by Franky On October 1, 2009
Hello, if I open the file the first time works fine, but when tried a second time, got the error: The RPC server is unavailable. (Exception from HRESULT: 0x800706BA).
Any ideas?
Thanks,
Franky
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.