Word文档未关闭

时间:2016-06-15 08:39:24

标签: c# .net ms-word office-interop exit

我有一个小程序打开word文档,对表进行一些更改,将其导出为PDF,然后关闭文档和应用程序。当我再次打开文档时,它仍然在表格中进行了原始更改。它看起来像是以某种方式缓存。这是我的代码:

private void Open()
{
    appWord = new Microsoft.Office.Interop.Word.Application();
    appWord.DisplayAlerts = WdAlertLevel.wdAlertsNone;
    string path = Environment.CurrentDirectory + "\\Resources\\document1.docx";
    wordDocument = appWord.Documents.Open(path);
}      

从某些表中删除一些行并导出为PDF

private void Close()
{
    object missing = Type.Missing;
    object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;
    wordDocument.Close(doNotSaveChanges, missing, missing);
    System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDocument);
    appWord.Quit(ref doNotSaveChanges, ref missing, ref missing);
    System.Runtime.InteropServices.Marshal.ReleaseComObject(appWord);
}

我是否以错误的方式关闭了文档?还是被缓存?某个临时文件保存在哪里?我没有打开任何其他单词流程。

3 个答案:

答案 0 :(得分:1)

更改未保存,因为当您关闭文档时,您告诉它不要保存更改。

object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;
wordDocument.Close(doNotSaveChanges, missing, missing);

请改为尝试:

object saveChanges = WdSaveOptions.wdSaveChanges;
wordDocument.Close(saveChanges, missing, missing);

答案 1 :(得分:0)

我们在关闭Word文档时实际使用以下(缩短的)代码:

object varFalse = false;
object missing = System.Type.Missing;

if (m_wordDoc != null)
{
    ((Microsoft.Office.Interop.Word.Document)m_wordDoc).Close(ref varFalse, ref missing, ref missing);
    //m_wordDoc = null;
}
if (m_wordApp != null)
{
    ((Microsoft.Office.Interop.Word.Application)m_wordApp).Quit(ref varFalse, ref missing, ref missing);
    //m_wordApp = null;
}

您会注意到我们对第一个参数使用bool值。不过,上面的代码正确地关闭了文档和Word实例。

但是,在我们执行操作并将其导出为PDF之前,我们会创建模板Word文件的临时副本。可能是导出文件为PDF会隐式保存原文,这对我们来说无关紧要,因为我们在处理后删除了临时文件。

答案 2 :(得分:-1)

您可能在任务管理器中打开了一些不需要的Word实例。

.Net中的COM的Workink需要释放com对象。更重要的是,在.Net中使用word interop(或任何其他COM对象)时,不能使用点,因为在点之间,临时对象是在场景后面创建的,需要释放。

例如:

wordDocument = appWord.Documents.Open(path);

应替换为

wordDocuments = appWord.Documents
wordDocument = wordDocuments.Open(path);

// Once done, you need to release those objects
System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDocument);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDocuments);

您可以查看this post,这些规则与excel相同。