[英]How to check an excel workbook is already open in C# win forms
我在应用程序中打开多个Excel文件。 有些会在应用程序启动时自动打开,而有些则会在运行时打开。
现在,我想通过单击按钮从Excel文件中获取数据。 但是在打开它之前,我想检查excel文件是否已经打开。
但是在两种情况下,我都不想在阅读后关闭文件。
我正在使用这种方法打开excel文件。
objExcel = new Excel.ApplicationClass();
objWorkbook = objExcel.Workbooks.Open(...);`
请帮助我是C#的新手。
如果我完全理解,您实际上想查找该Winform应用程序是否已打开某些文件,对吗?
如果是这样,我认为应该相当简单-只需将打开的工作簿缓存到某个字典中即可:
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中检索所有打开的工作簿,但是,有时会抛出一些异常(不确定为什么,但是我之前遇到过)。
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-Files OpenXML。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.