如何检查Excel工作簿已经在C#win表格中打开

我在我的应用程序中打开多个Excel文件。 有些会在应用程序启动时自动打开,有些则在运行时打开。

现在我想从button点击一个Excel文件中获取数据。 但是在打开之前,我想检查一下excel文件是否已经打开。

  1. 如果是开放的 ,我想直接阅读。
  2. 如果它没有打开 ,我想打开它并从中读取。

但在这两种情况下,我都不想在阅读后closures文件

我正在用这个方法打开excel文件。

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

请帮助我是C#的新手。

如果我正确地理解,你实际上是想find一些文件是否已经被这个winform应用程序打开了,对吧?

如果是这样,我认为它应该是相当简单的 – 只要将打开的工作簿caching到一些字典或其他:

  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 } 

另外,也可以使用excel应用程序的单个实例,然后所有打开的工作簿都可以从App.Workbooks中caching,但是它有时会抛出一些exception(不知道为什么,但我以前遇到过)。

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

实际上,调用IsFileLock方法来检查文件是否已被其他应用程序打开仍是值得的,否则可能会遇到一些错误。

如果您有读写权限,您可以检查:

  /// <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; } 

该代码来自StackOverflow上的其他人。

做.xlsx? 如果是这样,你可以用来读写Excel文件OpenXML。