【问题标题】:How to check an excel workbook is already open in C# win forms如何检查 Excel 工作簿是否已在 C# winforms 中打开
【发布时间】:2016-02-19 04:20:47
【问题描述】:

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

现在我想通过单击按钮从 Excel 文件中获取数据。但在打开之前,我想检查一下excel文件是否已经打开。

  1. 如果是open,我想直接从中读取。
  2. 如果它未打开,我想打开它并从中读取。

但在这两种情况下,我都不想在阅读后关闭文件。`

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

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

请帮助我是 C# 新手。

【问题讨论】:

标签: c# excel


【解决方案1】:

如果我理解正确的话,你其实是想看看这个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 方法来检查文件是否已经被其他应用打开了,否则你可能会遇到一些错误。

【讨论】:

  • 这个答案是有限的,因为它不处理通过其他方式打开工作簿的情况,在这种情况下调用 Open() 会产生异常。我们仍然需要 Workbook 对象。
【解决方案2】:

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

        /// <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 吗?如果是这样,您可以使用 OpenXML 来读写 Excel-Files。

【讨论】:

  • 什么意思?如果他有读写权限,则不会打开 excel 文件。因为excel总是锁定打开的文件。
  • 正如其他人所说,如果打开文件,Excel会锁定文件以防止非法修改
  • 这个检查一定要进行,如果 Excel 文档在别处打开,将会有 Excel 发布的消息框,您无法在应用程序中控制。 Excel-C# 界面只有在 Excel 文件可以在写入模式下打开时才能以受控方式工作(假设您要从 C# 中写入)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-08
  • 1970-01-01
  • 2016-03-01
  • 2012-03-24
  • 1970-01-01
相关资源
最近更新 更多