【问题标题】:C# save word document without prompt give 'document is opened elsewhere error'C#保存word文档而不提示给出'文档在别处打开错误'
【发布时间】:2013-10-01 21:26:31
【问题描述】:

我有一个带有 Office Word 的 Windows 窗体。我正在使用代码以编程方式打开 word 文档(_wd 的类型为 Microsoft.Office.Interop.Word.ApplicationClass - 我使用的是 VS 2012、.NET 4.5、Office 2007):

 public void LoadComponent(string path)
    {            
        if (_wd.Documents.Count != 0) _wd.ActiveDocument.Close(); 
        _wd.Documents.Add(ref path);
    }

我想保存活动文档时出现问题。我不希望出现保存提示 - 这是我尝试过的,但无法取消提示对话框:

_wd.ActiveDocument.Saved = true;
_wd.ActiveDocument.Save();

如果我尝试:

_wd.ActiveDocument.SaveAs(_filePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing, Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing, Type.Missing, Type.Missing);

我收到异常:“Word 无法保存此文件,因为它已在其他地方打开。” - 但它只在我的应用程序中打开,没有其他地方。如何以编程方式保存在没有保存提示对话框的情况下打开的 Word 文档?有趣的是,即使我尝试通过按“保存”按钮来保存文档,我也会收到保存提示对话框-> 就像之前没有在光盘上创建文档一样。但是,文档是从光盘打开的,只能以编程方式打开。如果我用 Word 打开文档,然后按“保存”,我永远不会得到保存提示对话框。

【问题讨论】:

  • 嗯,这是可能的。您多久创建一次_wd 的 实例?只需执行一次即可避免麻烦。

标签: c# ms-word ms-office office-interop


【解决方案1】:

我收到异常:'Word 无法保存此文件,因为它已经 在别处打开。'

只有当您的文档在另一个 Application 实例中打开时,您才会收到此信息。

以下示例适用于我,不会提示:

var path = @"C:\Temp\temp.docx";

Word.Application wordApp = new Word.Application();
Word.Documents documents = wordApp.Documents;
Word.Document doc = documents.Add(path);
doc.Range().Text = "Test Text";
doc.SaveAs2(path);
wordApp.Quit();

在您的任务管理器中检查 WINWORD.EXE 进程的杂散实例。如果Application 的实例未正确关闭(以编程方式),则可能会发生这种情况。

这些杂散进程之一可能使您的Document 处于打开状态。

【讨论】:

  • 你说得对——我打开了任务管理器,发现里面打开了很多 WINWORD.EXE 进程。当我关闭我的申请时,我并没有关闭这些流程,它们以某种方式保存了我的文件。只有一个 WINWORD.EXE,我保存时没有提示,也没有“文档已在其他地方打开”警告。
【解决方案2】:

似乎你不是唯一一个经历它的人。 可能是 MSWORD 中的错误。 如建议here

·         Click on start->run.
·         Type %appdata% and click ok.
·         Go to Microsoft->templates folder and delete Normal.dotm.
·         Restart word

【讨论】:

    猜你喜欢
    • 2020-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-03
    • 1970-01-01
    相关资源
    最近更新 更多