C#保存word文档而不提示'文件在别处打开错误'

时间:2013-10-01 21:26:32

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

我有一个带有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打开文档,然后按“保存”,我从未得到保存提示对话框。

2 个答案:

答案 0 :(得分: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开启。

答案 1 :(得分:0)

似乎你并不是唯一遇到它的人。 可能是MS WORD中的错误。 正如建议here

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