简体   繁体   English

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

[英]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.

相关问题 如何处理在 Nx open 中打开文件错误 - How to handle opening file error in Nx open 打开Excel文件时出错 - error when opening excel file NPOI Excel 文件无效的文件格式或扩展名 - NPOI Excel File invalid file format or extension 在 excel 2007 中打开时,Excel 电子表格生成导致“文件格式与扩展名错误不同” - Excel spreadsheet generation results in “different file format than extension error” when opening in excel 2007 从Excel文件中替换无效的XML字符并将其写回到磁盘会导致文件损坏在MS Excel中打开时出错 - Replacing Invalid XML characters from an excel file and writing it back to disk causes file is corrupted error on opening in MS Excel 从 C# 桌面应用程序打开以编程方式生成的 Excel 文件时出现 C# 错误:“文件格式或文件扩展名无效” - C# Error while opening programmatically generated Excel file from a C# desktop application: "File format or file extension is not valid" EPPlus 打开 excel .xlsx 文件错误 - EPPlus opening excel .xlsx file error 打开导出的Excel文件时出现错误消息 - Error message while opening exported excel file 打开与Excel文件的连接时发生未指定的错误 - Unspecified error when opening connection with excel file 打开由NPOI创建的Excel文件时出错 - Error while opening the excel file created by NPOI
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM