[英]In Excel automation, how to gracefully handle invalid file format error upon file opening?
I'm trying to open a Microsoft Excel file in a C# program using the 'excelApp.Workbooks.Open()' method. 我正在尝试使用excelApp.Workbooks.Open()方法在C#程序中打开Microsoft Excel文件。 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? 那么,Excel API中是否存在允许这种验证的另一种方法?
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. 如果无法打开工作簿,则返回值为空。
(ie Workbook wkb = Workbooks.Open(....); wkb will be null when DisplayAlerts = False and the file could not be opended) (即,Workbook wkb = Workbooks.Open(....);当DisplayAlerts = False并且无法打开文件时,wkb将为空)
This is purely based on what I understand of excel object model. 这完全基于我对excel对象模型的了解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.