在Excel自动化中,如何优雅地处理文件打开时的无效文件格式错误?

发布于 2024-07-10 23:12:23 字数 282 浏览 4 评论 0原文

我正在尝试使用“excelApp.Workbooks.Open()”方法在 C# 程序中打开 Microsoft Excel 文件。 事实上,如果文件格式无效,此方法会导致显示错误消息框。 然而,我不希望这样; 我希望在我自己的代码中优雅地处理这个错误。

我的问题是,我该怎么做?

上面的方法不会抛出任何我可以捕获的异常。 即使确实如此,仍然存在那个讨厌的消息框。 因此,也许唯一的方法是在打开文件格式之前对其进行验证。 那么,Excel API 中是否有另一种方法允许进行此类验证呢?

I'm trying to open a Microsoft Excel file in a C# program using the 'excelApp.Workbooks.Open()' method. As it happens, if the format of the file is invalid, this method causes an error message box to be displayed. I, however, don't want that; I wish to handle this error gracefully in my own code.

My question is, how do I do that?

The above method doesn't throw any exception which I can catch. Even if it did, there's still that pesky message box anyway. So perhaps the only way would be to validate the file format before opening it. Is there, then, another method in Excel API to allow such validation?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

征﹌骨岁月お 2024-07-17 23:12:23

抱歉,我无法使用 Excel 2007 模拟损坏的 xls 文件示例。

在调用 Workbooks.Open 之前尝试 Application.DisplayAlerts = False...

如果无法打开工作簿,则返回值将为 null。< br>
(即工作簿 wkb = Workbooks.Open(....);
当 DisplayAlerts = False 且文件无法打开时,wkb 将为 null)

这纯粹是基于我对 Excel 对象模型的理解。

I am sorry, I am not able to simulate the corrupt xls file example with Excel 2007.

Try Application.DisplayAlerts = False before calling Workbooks.Open...

If the workbook can't be opened, the returned value will be null.
(i.e. Workbook wkb = Workbooks.Open(....);
wkb will be null when DisplayAlerts = False and the file could not be opended)

This is purely based on what I understand of excel object model.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文