Checking if an Excel Workbook is open

后端 未结 7 1074
孤街浪徒
孤街浪徒 2020-12-30 05:22

Is there a way to see if an Excel Workbook, say DataSheet.xls, is open (in use) or not? I would like to close that Workbook if it is opened.

7条回答
  •  隐瞒了意图╮
    2020-12-30 06:03

    This function below will return you whether the excel file is open or not.

    Second function will get you the Excel Application, Workbook & Sheet to be used for your code.

    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using wf = System.Windows.Forms;
    using xl = Microsoft.Office.Interop.Excel;
    
    public static class ExcelTest
    {   
        public xl.Application xlApp = null;
        public xl.Workbook xlWb = null;
        public xl.Worksheet xlWs = null;
    
        public static bool IsXlFileOpen(string xlFileName)
        {       
            try
            {       
                if (!File.Exists(xlFileName))
                {
                    wf.MessageBox.Show("Excel File does not exists!");
                    return false;
                }
    
                try
                {
                    xlApp = (xl.Application)Marshal.GetActiveObject("Excel.Application");
                }
                catch (Exception ex)
                {
                    return false;
                }
    
                foreach (xl.Workbook wb in xlApp.Workbooks)
                {
                    if (wb.FullName == xlFileName)
                    {
                        xlWb = wb;
                        return true;
                    }
                }
    
                return false;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    
        public static void GetXlSheet(string xlFileName,
                                        string xlSheetName)
        {
            try
            {
                if (!File.Exists(xlFileName))
                {
                    wf.MessageBox.Show("Excel File does not exists!");
                    return false;
                }
    
                xlApp = (xl.Application)Marshal.GetActiveObject("Excel.Application");
                foreach (xl.Workbook wb in xlApp.Workbooks)
                {
                    if (wb.FullName == xlFileName)
                    {
                        if (!xlWb
                            .Sheets
                            .Cast()
                            .Select(s => s.Name)
                            .Contains(xlSheetName))
                        {
                            wf.MessageBox.Show("Sheet name does not exist in the Excel workbook!");
                            return;
                        }
                        xlWs = xlWb.Sheets[xlSheetName];
                    }
                }
            }
            catch (Exception ex)
            {
                // catch errors
            }
        }   
    }
    

提交回复
热议问题