Create a Word document in C#

Create a Word document

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);

    // 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.";

    // 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.Font.Name = old_font;

    // Save the document.
    object filename = Path.GetFullPath(
        Path.Combine(Application.StartupPath, "..\\..")) +
    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 Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in interoperability, Office, Word and tagged , , , , , , , , , , , , . Bookmark the permalink.

12 Responses to Create a Word document in C#

  1. Pingback: Add a picture to a Word document in C# - C# HelperC# Helper

  2. Manav says:


  3. Sunny says:

    can v add a paragraph on x,y position in document.

    • RodStephens says:

      I’m not sure how you would do that. You can insert a paragraph at a position in the document, for example, after an existing paragraph. But inserting one at an (x, y) position isn’t what Word normally does.

      One way to do this might be to create a TextBox and then insert text into it.

      You might try recording a macro while you insert text where you want it and then look at its code to see how it worked.

  4. John says:

    Nice example, thank you. I especially like the explanation of the quirkiness of the interaction between C# and the Word object model (the byref thingy etc)

  5. Dan Miller says:

    Hello dear friend , you can try ZetWord SDK

  6. Antony Bruno says:

    I am using this an advance word document processing API for .NET application.

  7. prabhu says:

    I need few thinks addition to this
    My requirement is creating word file with header , table and text all this i am getting from list class
    If i got 30 list
    for each list i want each page for ex 30 page i want
    Please help on this

    Current Scenario i am getting only one page overwriting all list finally shows last list content


  8. Pingback: Make a Word document with multiple pages in C# - C# HelperC# Helper

  9. Sid says:

    Is it possible to use this library to edit an existing word template by using bookmarks?
    I tried using the ‘Bookmarks.Item’ but it doesn’t seem to be working.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.