Create and Edit Office Documents with .NET, Page 2
The following code saves a Word document:
doc.SaveAs(ref fileToSave,
ref Missing, ref Missing, ref Missing, ref Missing,
ref Missing, ref Missing, ref Missing, ref Missing,
ref Missing, ref Missing, ref Missing, ref Missing,
ref Missing, ref Missing, ref Missing);
Be sure to close both the document and the Word application before you quit your application. You can do that as follows:
doc.Close(ref Missing, ref Missing, ref Missing); app.Quit(ref Missing, ref Missing, ref Missing);
Lastly, you need to know how to create a new Word document. After getting a new application instance, enter the following:
Word.Document doc = app.Documents.Add( ref objMissing, ref objMissing, ref objMissing, ref objMissing); doc.Activate();
You first add a new document to the Documents collection of the application and activate it. Next, you start typing text using the methods of the Selection object:
app.Selection.TypeText("This is a sample Word document");
app.Selection.TypeParagraph();
No Easy Task
Creating and editing Office documents from within .NET applications is not as easy as it should be. The main obstacle remains the different programming models—COM versus .NET—that wrapper tools can't always hide. Add to this the inherent complexity of the Word (or Excel) object models and you get a clear picture of why programming Office applications is complex and boring.
Whichever approach you choose, you can't perform any step without a good understanding of the Office applications object models. In addition, if you use VSTO, strong knowledge of .NET security and deployment issues is required.
Resources
- Understanding the Excel Object Model from a .NET Developer's Perspective
- Understanding the Word Object Model from a .NET Developer's Perspective
About the Author
Dino Esposito is Wintellect's ADO.NET expert and a trainer and consultant based in Rome, Italy. He runs the Cutting Edge column for MSDN Magazine and is a regular contributor to MSDN News, Visual C++ Developers Journal, and SQL Server Magazine.
