在.net中结束Excel,Word进程

 

protected string createExcel()
    {
        string strExcelName;
        string strTemplatePath;
        System.Data.DataTable dt = new System.Data.DataTable();
        DateTime startTime = DateTime.Now;       
        Excel.Application app = new ApplicationClass();
        DateTime endTime = DateTime.Now;
        Excel.Workbook wb;
        object missing = System.Reflection.Missing.Value;
         ……

        try
        {  
            
            strTemplatePath = Server.MapPath("../Module/po002.xlt");
            strExcelName = DateTime.Now.ToString("yyyyMMddHHmmss") + @".xls";
            wb = app.Workbooks.Open(strTemplatePath, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
            app.Visible = false;

          …………

         …………

            Excel.Worksheet sheetTest = (Excel.Worksheet)wb.Worksheets["2"];
            sheetTest.Visible = XlSheetVisibility.xlSheetHidden;

            wb.SaveAs(strExcelName, missing, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing);

             System.Runtime.InteropServices.Marshal.ReleaseComObject(sheetTest);
            wb.Close(null, null, null);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
            app.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(app);

        }
        catch (Exception exCreateExcel)
        {
            throw new Exception(exCreateExcel.Message);
        }
        finally
        {
            killProcess(startTime, endTime,"Excel");
           
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
       
        return strExcelName;
    }

 

  protected void killProcess(DateTime start,DateTime end,string ProcessName)
    {
        Process[] myProcesses;
        DateTime ProStartTime;
        myProcesses = Process.GetProcessesByName(ProcessName);

        //因为暂时没有想到得到Excel进程ID的方法,所以只能判断进程启动时间
        foreach (Process myProcess in myProcesses)
        {
            ProStartTime = myProcess.StartTime;
            //myProcess.Id

            if (start <= ProStartTime && ProStartTime <= end)
            {
                myProcess.Kill();
            }
        } 
    }

请注意红色代码:)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值