简体   繁体   中英

How to check an excel workbook is already open in C# win forms

I am opening multiple excel files in my application. Some will be automatically open when the application starts whereas some are opening at the run time.

Now I want to get data from an excel file on a button click. But before opening it, I want to check that excel file is already open.

  1. If it is open , I want to read from it directly.
  2. if it is not open , I want to open it and read from it.

But in both the cases I don't want to close the file after reading.`

I am using this method to open excel file.

objExcel = new Excel.ApplicationClass();
objWorkbook = objExcel.Workbooks.Open(...);`

Please help I am new to C#.

if i understand corectly, you actually want to find whether some files are already open by this winform application, right?

if so, i think it should be fairly simple - just cache the opened workbook to some dictionary or so:

    static Dictionary<string, Workbook> _openedWorkBooks = new Dictionary<string, Workbook>();    
    public static Workbook GetWorkbook(string filePath)  {    
        Workbook wkb = null;    
        if (!(_openedWorkBooks.TryGetValue(filePath, out wkb)))    
        {
            // Open the file and store it into the dictionary    
        }

        return wkb;  
    }

    // remember to remove it when it's closed  
    public static CloseWorkbook()  
    {    // need to remove the corresponding key from the dictionary  
    }

also, you could use single instance of excel application too, and then all the opened workbook could be rerieved from App.Workbooks, however, it throws some exception sometimes (not sure why, but i did encounter before).

  var app = new Microsoft.Office.Interop.Excel.Application(); var bk1 = app.Workbooks.Open("c:\\temp\\myfile.xls"); var allOpenBks = app.Workbooks; 

Actually it's still worth to call IsFileLock method to check the file is already open by other apps, otherwise you could encounter some errors.

You can checkk, if you have Read-Write access:

        /// <summary>
    /// Check wether a file is locked
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    public static bool IsFileLocked(FileInfo file)
    {
        FileStream stream = null;

        try
        {
            stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        }
        catch (IOException)
        {
            //the file is unavailable because it is:
            //still being written to
            //or being processed by another thread
            //or does not exist (has already been processed)
            return true;
        }
        finally
        {
            if (stream != null)
                stream.Close();
        }

        //file is not locked
        return false;
    }

The Code is from some one else on StackOverflow.

Do .xlsx? If so, you can use for reading and writing Excel-Files OpenXML.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM