zoukankan      html  css  js  c++  java
  • C# Excel打开多个文件时用程序关闭指定一个文件(不是杀掉进程)

    private void button1_Click(object sender, EventArgs e)
    {
        CloseExcelWorkbook("TestReport.xlsx");
    }
    
    //put the following abbreviation to the "using" block: using Excel = Microsoft.Office.Interop.Excel;
    internal void CloseExcelWorkbook(string workbookName)
    {
        try 
        {           
            Process[] plist = Process.GetProcessesByName("Excel", ".");
            if (plist.Length  > 1)
                throw new Exception("More than one Excel process running.");
            else if (plist.Length == 0)
                 throw new Exception("No Excel process running.");
    
            Object obj = Marshal.GetActiveObject("Excel.Application");
    
            Excel.Application excelAppl = (Excel.Application)obj;
    
            Excel.Workbooks workbooks = excelAppl.Workbooks;
            foreach (Excel.Workbook wkbk in workbooks )
            {
                if (wkbk.Name == workbookName)
                    wkbk.Close();
            }
            //dispose
            //workbooks.Close(); //this would close all workbooks
            GC.Collect();
            GC.WaitForPendingFinalizers();
            if (workbooks != null)
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(workbooks);
            //excelAppl.Quit(); //would close the excel application
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excelAppl);
            GC.Collect();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    注意  如果由于以下 Marshal.GetActiveObject("Excel.Application")  出错.则不要用管理员身份运行即可,(多进程时测试中发现是可以关闭对应的)

  • 相关阅读:
    2-4 递增链表的插入 链表
    KMPnext数组自看
    Shortest Prefixes POJ
    Xor Sum HDU
    Immediate Decodability HDU
    Repository HDU
    "strcmp()" Anyone? UVA
    Remember the Word UVALive
    A Magic Lamp HDU
    Check Corners HDU
  • 原文地址:https://www.cnblogs.com/itstac/p/13968470.html
Copyright © 2011-2022 走看看