【问题标题】:Excel file remaining locked for editing after useExcel 文件在使用后仍处于锁定状态以供编辑
【发布时间】:2020-06-16 00:09:53
【问题描述】:

我有一个带有OpenFileDialog 的 Windows 窗体应用程序。用户单击“处理”按钮,应用程序将浏览文件(一个 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

【问题讨论】:

  • 在此处阅读注释的第二部分:Get running instances of Excel 并查看指向其他 SO 答案的链接,这些答案显示其他人如何解决相同的问题。
  • 也许可以考虑尝试/最后。您可以将Close() 代码放在 finally 块中。
  • @tgolisch - 我使用什么Close() 代码?还是一样的Dispose() 我已经打电话了?
  • OpenFileDialog1.OpenFile 返回一个 Stream 对象。尝试使用Using strm As IO.Stream = OpenFileDialog1.OpenFile ... End Using 包装您的代码,然后将strm 传递给New ExcelPackage 构造函数。
  • @TnTinMn - Yahtzee!那成功了。如果您将其放入答案中,我会接受。

标签: excel vb.net winforms openfiledialog excelpackage


【解决方案1】:

OpenFileDialog.OpenFile Method 返回一个 Stream 对象,该对象可能没有被 ExcelPackage 关闭。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    相关资源
    最近更新 更多