8

I have a Word document, letter.docx, that is a letter I intend to mail to hundreds of people for a party. The letter is already composed and has been formatted in its own special way with varying type sizes and fonts. It's set and ready to go, with placeholders where I have to fill out variables that change like Name, Address, phone number, etc.

Now, I would like to write a C# program where a user can type in variable things like Name, Address, etc., into a form, hit a button, and produce letter.docx with the right information filled in at the right places.

I understand Word has features that allow you do this, but I really want to do this in C#.

B.K.
  • 9,982
  • 10
  • 73
  • 105
MrPatterns
  • 4,184
  • 27
  • 65
  • 85

4 Answers4

12

Of course you can do it. Use Microsoft.Office.Interop.Word reference in your project.

First bookmark all the fields you want to be updated in the document from 'insert' tab (eg. NameField is bookmarked with tag 'name_field'). Then, in your C# code add the following:

Microsoft.Office.Interop.Word.Application wordApp = null;
wordApp = new Microsoft.Office.Interop.Word.Application();
wordApp.Visible = true;

Document wordDoc = wordApp.Documents.Open(@"C:\test.docx");
Bookmark bkm = wordDoc.Bookmarks["name_field"];
Microsoft.Office.Interop.Word.Range rng = bkm.Range;
rng.Text = "Adams Laura"; //Get value from any where

Remember to properly save & close the document.(You can see this)

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
pxm
  • 1,611
  • 2
  • 18
  • 34
1

I don't know of anything built into the language, but the example here seems to do exactly what you want.

If you can provide specific examples of what you want to do (are the placeholders Fields? specifically name bits of text?), I can probably give you a more refined answer that directly targets your problem.

Sean Duggan
  • 1,105
  • 2
  • 18
  • 48
  • The placeholders are not Fields, with a capital F, because I don't know what Fields are. It seems to hold a special meaning. Basically, I have formatted text and would like to swap out/swap in names, addresses, and phone numbers from a list. – MrPatterns Mar 10 '14 at 14:31
  • Ah. That would just be searching and replacing. The link I have above is doing exactly that with their library. It looks like there's also [example code on SO](http://stackoverflow.com/questions/5651464/c-sharp-word-replace-with-formating?rq=1) doing this. Looks pretty straightforward. :) – Sean Duggan Mar 10 '14 at 14:49
  • You can have dummy text in your document (formatted to your liking), bookmark them & then access them from C# and set their values. – pxm Mar 12 '14 at 07:00
1

Word Provides COM objects that one can make use of in C#

Add a reference to the Microsoft office interop under the COM tab in the add reference dialog

Also, see this question:

Filling in FIelds in work using C#

Community
  • 1
  • 1
Michael Kniffen
  • 346
  • 2
  • 7
1

I had a situation where I needed to fill out some MS Word forms, so I used something similar to the following code (make sure you reference Microsoft.Office.Interop.Word; I used version 14, but you should adjust it to your own scenario):

// FormData is a custom container type that holds data... you'll have your own.
public static void FillOutForm(FormData data)
{
    var app = new Microsoft.Office.Interop.Word.Application();
    Microsoft.Office.Interop.Word.Document doc = null;

    try 
    {
        var filePath = "Your file path.";
        doc = app.Documents.Add(filePath);
        doc.Activate();

        // Loop over the form fields and fill them out.
        foreach(Microsoft.Office.Interop.Word.FormField field in doc.FormFields)
        {
            switch (field.Name)
            {
                // Text field case.
                case "textField1":
                    field.Range.Text = data.SomeText;
                    break;
                // Check box case.
                case "checkBox1":
                    field.CheckBox.Value = data.IsSomethingTrue;
                    break;
                default:
                    // Throw an error or do nothing.
                    break;
            }
        }

        // Save a copy.
        var newFilePath = "Your new file path.";
        doc.SaveAs2(newFilePath);
    }
    catch (Exception e)
    {
        // Perform your error logging and handling here.
    } 
    finally
    {
        // Make sure you close things out.
        // I tend not to save over the original form, so I wouldn't save 
        // changes to it -- hence the option I chose here.
        doc.Close(
            Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges);
        app.Quit();
    }
}

As you can see, it's really not that hard at all. There are some other options on forms, so you'll have to research them, but the most general ones, the check box and the text box, are the ones I demonstrated here. If you didn't create a form, I suggest going through and making sure that you know all the fields, as that's what you'll need for this.

B.K.
  • 9,982
  • 10
  • 73
  • 105