Title: Create a Word document in C#
This example shows how to make a C# program create a Word document. First open the Add References dialog. On the COM tab, select "Microsoft Word 14.0 Object Library" (or whatever version you have installed on your system).
Add the following using statement to make working with the Word namespace easier. The Word = part means you can use Word as an alias for the namespace.
using Word = Microsoft.Office.Interop.Word;
This example uses the following code to create a new Word document and add text to it.
// Make a Word document.
private void btnGo_Click(object sender, EventArgs e)
{
// Get the Word application object.
Word._Application word_app = new Word.ApplicationClass();
// Make Word visible (optional).
word_app.Visible = true;
// Create the Word document.
object missing = Type.Missing;
Word._Document word_doc = word_app.Documents.Add(
ref missing, ref missing, ref missing, ref missing);
// Create a header paragraph.
Word.Paragraph para = word_doc.Paragraphs.Add(ref missing);
para.Range.Text = "Chrysanthemum Curve";
object style_name = "Heading 1";
para.Range.set_Style(ref style_name);
para.Range.InsertParagraphAfter();
// Add more text.
para.Range.Text = "To make a chrysanthemum curve, " +
"use the following parametric equations as t goes " +
"from 0 to 21 * ? to generate " +
"points and then connect them.";
para.Range.InsertParagraphAfter();
// Save the current font and start using Courier New.
string old_font = para.Range.Font.Name;
para.Range.Font.Name = "Courier New";
// Add the equations.
para.Range.Text =
" r = 5 * (1 + Sin(11 * t / 5)) -\n" +
" 4 * Sin(17 * t / 3) ^ 4 *\n" +
" Sin(2 * Cos(3 * t) - 28 * t) ^ 8\n" +
" x = r * Cos(t)\n" +
" y = r * Sin(t)";
// Start a new paragraph and then
// switch back to the original font.
para.Range.InsertParagraphAfter();
para.Range.Font.Name = old_font;
// Save the document.
object filename = Path.GetFullPath(
Path.Combine(Application.StartupPath, "..\\..")) +
"\\test.doc";
word_doc.SaveAs(ref filename, 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);
// Close.
object save_changes = false;
word_doc.Close(ref save_changes, ref missing, ref missing);
word_app.Quit(ref save_changes, ref missing, ref missing);
}
The code first creates an instance of Word.ApplicationClass. Notice that the variable has the odd type Word._Application containing an underscore. (There's also an Application class without the underscore, but if you use that one, C# gets a little confused about some ambiguously named methods.)
This example makes the Word server visible. In a real application, you might want to keep it hidden.
The Word object model uses many method calls that for some reason take lots of parameters by reference even though they are not modified by the methods. That means you must put the values for those parameters in variables. For example, you cannot use true as a boolean parameter because you cannot pass a constant by reference. Similarly you can't use a literal string such as C:\wherever\test.doc for the name of the file you are opening because that is not an assignable variable.
The code creates a special variable named missing that has value Type.Missing. The code can use this value for any optional parameters that it doesn't need to pass to the Word methods. The program then uses it in a call to the Word server's Documents.Add call, which creates a new Word document.
Now the program starts adding text to the document. It adds a Paragraph object to the document's Paragraphs collection.
One of the more important objects in Word is Range. A Range represents a chunk of a document. The code sets the new paragraph's text to "Chrysanthemum Curve." It then sets the Range object's style to "Heading 1." Again notice the odd way it must place the value in a variable before calling set_Style so it can pass the style's name by reference.
The code then calls the Range object's InsertParagraphAfter method. That adds a paragraph mark after the Range object's current text and updates the Range so it advances to the new paragraph. Now the Range is ready to add more text after the first paragraph.
The code sets the Range object's text again to add new text and calls InsertParagraphAfter again.
Next the code adds some text formatted as code with the font Courier New. It saves the current font's name and sets the Range object's font to Courier New. From now on, new text will have this font.
The code again sets the Range object's text and adds a new paragraph mark. It then restores the original font name so future text will be in the original font.
Next the code calls the Word document's SaveAs method to save the new document. This overwrites any existing file with that name without any warning. If you want to be sure the file doesn't already exist, use File.Exists to check.
Finally the code closes the Word document and the Word application.
Much of the work in this kind of Office automation is figuring out what objects and methods in the Office object model do the things you want. For example, figuring out how to use Word's InlineShape and Shape objects to create and format a picture. If you want to do a lot of this, my book Microsoft Office Programming: A Guide for Experienced Developers may help. The code is in Visual Basic and it's a few years old, but it should help you figure out how to manipulate the Word, Excel, PowerPoint, Access, and Outlook object models, and those models haven't changed too much since the book was written. |
Download the example to experiment with it and to see additional details.
|