Excel 文件在使用后保持锁定状态以供编辑

Excel file remaining locked for editing after use

我有一个带有 OpenFileDialog 的 Windows Forms 应用程序。用户单击 "Process" 按钮,应用程序遍历文件 - Excel 电子表格 - 并处理其中的数据。所有这些都按预期工作,但有一个警告。

应用程序完成处理后,文件仍处于锁定状态以供编辑,因此当我打开文件进行更改时,我收到此消息:

如果我完全关闭应用程序,文件将被解锁,所以我假设应用程序保留文件的时间超过了应有的时间。我猜应该有某种 Close() 方法或可以释放资源的东西,但我无法弄清楚我到底需要什么。我尝试使用 Dispose() 并将我的代码包装在 Using 块中,我认为这会自动破坏所有内容但没有运气。

这是我的代码:

Using excel = New ExcelPackage(OpenFileDialog1.OpenFile)
    Dim ws = excel.Workbook.Worksheets.First()

    'Process data in ws...

    OpenFileDialog1.Dispose() 'Doesn't seem to release the file
    excel.Dispose() 'Doesn't seem to release the file
End Using

可能未被 Excel 包关闭的 OpenFileDialog.OpenFile Method returns a Stream 对象。

为确保流被释放,请使用以下模式。

Using strm As IO.Stream = OpenFileDialog1.OpenFile
  Using excel = New ExcelPackage(strm)
      ' ...
  End Using
End Using