C# 调用word进程操作文档关闭进程

程序后台调用word
设置word 可以被程序调用,其实就是权限问题,这个一般要设置服务器的用户和netword用户。到com组件里面设置。

操作word
1.

Microsoft.Office.Interop.Word._Application wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();  //新建对象,会产生一个新的word进程
 




2.

var wordDoc =wordApp.Documents.Open(ref filename)//打开word文档
 

3.

wordDoc.AcceptAllRevisions(); //接收word中所有的修订
wordDoc.Save();//保存
wordDoc.Close(ref missing, ref missing, ref missing);  //关闭word文档
 




 

执行上面三步,你会发现,这三个代码每执行一次,产生一个word进程。直至服务器资源耗尽崩溃!

管理word进程
 

解决方案:

1.

对Word._Application对象进行退出,这是最基本的,也是必须的。

 

wordApp.Application.Quit(ref saveOption, ref missing, ref missing);
 




2.倘若退出,进程还是存在,为了保险起见,我们还可以对进程进行kill。

 

//杀死打开的word进程
 Process myProcess = new Process();
 Process[] wordProcess = Process.GetProcessesByName("winword");
 

但是这里有一个问题,就是会误杀别的地方调用的进程。下面就可以杀死属于自己的进程。

 

foreach (Process pro in wordProcess) //这里是找到那些没有界面的Word进程
{
        IntPtr ip= pro.MainWindowHandle;

         string str =pro.MainWindowTitle; //发现程序中打开跟用户自己打开的区别就在这个属性
       //用户打开的str 是文件的名称,程序中打开的就是空字符串
         if (str==文件名)
           {
                  pro.Kill();
           }
           }
 


其实上面还有一个地方可以优化,存在现有的进程,不创建新的进程。

 

A程序叫B程序关闭,B程序有没有关闭是不可控的。  

如果word都是new出来的,那么会有越来越多的word进程。使用get的方式,保证只有一个word进程。  

try 

 { 

       this.app = (Application)Microsoft.VisualBasic.Interaction.GetObject(null, "Word.Application");  }  catch { 

                this.app = new Application();             

} 

 

public void DisposeExcelInstance()
{
    app.DisplayAlerts = false;
    workBook.Close(null, null, null);
    app.Workbooks.Close();
    app.Quit();
    if (workSheet != null)
        System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
    if (workBook != null)
        System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook);
    if (app != null)
        System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
    workSheet = null;
    workBook = null;
    app = null;
    GC.Collect(); // force final cleanup!
}

 

posted @ 2022-09-03 11:57  流氓大菠萝  阅读(1056)  评论(0编辑  收藏  举报