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

时间:2022-10-24 13:42:50

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.

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

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?

上面的方法没有抛出我能捕获的任何异常。即使它确实如此,仍然有那个讨厌的消息框。所以也许唯一的方法是在打开之前验证文件格式。那么,Excel API中有另一种允许这种验证的方法吗?

1 个解决方案

#1


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

对不起,我无法使用Excel 2007模拟损坏的xls文件示例。

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

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

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)

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

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

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

#1


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

对不起,我无法使用Excel 2007模拟损坏的xls文件示例。

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

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

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)

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

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

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