无法使用 .NET 更新 Microsoft Word 文档字段

发布于 2024-12-21 13:07:25 字数 3269 浏览 3 评论 0原文

目前,我正在尝试构建一个工具来打开 Microsoft Word 文档文件并更新文档中的所有字段。主要代码如下:

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

主函数调用 UpdateDocumentFieldsInFile()。当我单步执行代码时,它会打开文件并更新它,但是在程序退出并且我手动重新打开文件后,字段尚未更新。有人对如何解决这个问题有什么建议吗? TIA。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

香橙ぽ 2024-12-28 13:07:25

您似乎没有使用通过 OpenDocument 打开的文档。您的 Update 方法正在创建一个新文档(通过 Documents.Add),该文档将您的文件视为模板。这将创建一个新文档并对其进行编辑。因此,您实际上并没有在 Update 方法中操作位于 strFile 的文件。

当您单步执行代码时,正在更新的文档的名称是“Document1”吗?这将确认您没有编辑文件“测试字段更新(来自文档属性).docx”,而是使用该文件作为模板添加的新文档。

编辑:如果是我,我会把OpenDocument变成一个函数并返回打开的文档。然后将该文档传递到 Update 方法中,由于它已经打开,因此您无需再次打开或添加它。

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.

青春如此纠结 2024-12-28 13:07:25

再次感谢您的反馈,丹尼斯。在我确定我没有再次打开该文档后,由于某种我无法确定的原因,它仍然对我不起作用,所以我最终只是创建了一个程序,使用 Java Robot 来执行以下操作我需要:

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

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);
    }      
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文