user8128167
user8128167

Reputation: 7696

cannot update microsoft word document fields using .NET

Presently I am attempting to build a tool that will open a Microsoft Word document file and update all the fields in the document. Here is the main code:

using Microsoft.Office.Interop.Word;

public class clsDocumentFieldUpdateTool
{
    private static Microsoft.Office.Interop.Word.Application wordApp = null;
    private static Microsoft.Office.Interop.Word.Document oDoc = null;
    private static object missing = null;
    private static object readOnly = false;
    private static object visible = true;

    public static void OpenDocument(string docFileNameWithPath)
    {
        wordApp = new Microsoft.Office.Interop.Word.Application();
        missing = System.Reflection.Missing.Value;
        object fileToOpen = docFileNameWithPath;
        try
        {
            oDoc = wordApp.Documents.Open(ref fileToOpen, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref                     missing, ref visible, ref visible, ref missing, ref missing, ref missing);
        }
        catch (Exception excOpenFile)
        {
            MessageBox.Show(excOpenFile.Message +  System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + " - " + excOpenFile.StackTrace);
        }
    }

    private static void Update(string file)
    {
        object nothing = System.Reflection.Missing.Value; // our 'void' value
        object filename = file; // our word template
        object notTrue = false;  // our boolean false

        try
        {
            //
            // now we want to load the template and check how many fields there are to replace
            //
            wordApp.Visible = true;
            oDoc = wordApp.Documents.Add( // load the template into a document workspace
                                               ref filename,  // and reference it through our myWordDoc
                                               ref missing,
                                               ref missing,
                                               ref missing);
            dynamic properties = oDoc.BuiltInDocumentProperties;
            // count how many fields we have to update
            int fields = oDoc.Fields.Count;

            foreach (Field myField in oDoc.Fields)
            {
                myField.Select();
                myField.Update();
            }
            oDoc.Save();
            oDoc.Close(ref notTrue, ref missing, ref missing);
            wordApp.Application.Quit(   ref notTrue,
                                        ref missing,
                                        ref missing);
        }
        catch (Exception excException)
        {
            MessageBox.Show(excOpenFile.Message +  System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name + " - " + excException.StackTrace);
        }
    }

    public static void UpdateDocumentFieldsInFile()
    {
        string strFile = @"L:\admin\11ZG-0401\11-SWDev\Testing Field Updates (from Document Properties).docx";
        OpenDocument(strFile);
        Update(strFile);
    }
}

Where the main function calls UpdateDocumentFieldsInFile(). When I step through the code, it opens up the file and updates it, but after the program exits and I re-open the file manually, the fields have not been updated. Does anyone have any suggestions on how to resolve this? TIA.

Upvotes: 1

Views: 3010

Answers (2)

user8128167
user8128167

Reputation: 7696

Thanks again for the feedback, Dennis. After I made sure that I wasn't opening the document again it still wouldn't work for me for some reason that I haven't been able to determine, so I eventually just ended up creating a program that uses Java Robot to do what I needed:

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;

public class Robot06{
  static int keyInput[] = 
  {
    KeyEvent.VK_F11,
    KeyEvent.VK_F9
  };

  public static void main(String[] args) throws AWTException,IOException
  {
    Runtime.getRuntime().exec("winword L:\\admin\\11ZG-0401\\11-SWDev\\\"Testing Field Updates (from Document Properties).docx\"");
    Robot robot = new Robot();

    for (int cnt2 = 0; cnt2 < 10; cnt2++)
    {
      robot.keyPress(keyInput[0]);
      robot.delay(500);
      robot.keyPress(keyInput[1]);
      robot.delay(500);
    }      
  }
}

Upvotes: 0

CoderDennis
CoderDennis

Reputation: 13837

It looks like you're not using the document that's opened via OpenDocument. Your Update method is creating a new document (via Documents.Add) that treats your file as a template. That's going to create a new document and edit it. So you're not actually manipulating the file that's located at strFile within your Update method.

When you're stepping through the code, is the name of the document that is being updated "Document1"? That would be a confirmation that you're not editing the file "Testing Field Updates (from Document Properties).docx", but a new document that was added using that file as a template.

Edit: If it was me, I would turn OpenDocument into a function and return the opened document. Then pass that document into the Update method and since it's already opened, you don't need to open or add it again.

Upvotes: 1

Related Questions