views:

625

answers:

2

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?

+2  A: 

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.

shahkalpesh
Yup. That worked for me. Although it didn't return a null workbook reference, at least the messagebox didn't show up. Thanks.
Frederick
Please see my example code to trap the error.
lakshmanaraj
A: 

hi

xlWorkBook = xlApp.Workbooks.Open("youfile.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

http://csharp.net-informations.com/excel/csharp-open-excel.htm

thanks.

bolton