How to check if a file is a valid Excel spreadsheet?

I already did a search here on SO, on this , this , this and more, but there is no clue, so I have to ask you guys.

I am trying to open an Excel file through Interop and I have Office 2007 installed, so I am using Microsoft.Office.Interop.Excelversion 14.0.

When I try to open a valid file xls, everything works fine.

But if I try to open an invalid file (for example, a bitmap or an executable file) through Interop, Excel will open it without complaint or warning.

How can I detect that an invalid workbook file is installed in Excel without blocking with a warning?

I am trying to write unit test of my Excel object reader. One example is an attempt to open an invalid file.

Some code to help: Create an application:

    _app = new Application()
        {
            Visible = false,
            DisplayAlerts = false,     // <-- I don't want to remove this.
            AskToUpdateLinks = false,
        };

Opening a workbook:

   _workbooks.Open(filename);
   _workbook = _workbooks.get_Item(1); // 1-based.
   _worksheets = _workbook.Sheets;

EDIT: Just add one more info: Excel is loading an invalid file. If the parameter is DisplayAlertsset to true, it complains (open a dialog box), informing that the workbook seems to be damaged, but if the parameter is DisplayAlertsset to false, it downloads the file as shown below:

Excel Loads Invalid File

+5
source share
2 answers

I just finished using a different approach: Excel workbooks have a property FileFormat. When Excel opens an invalid file, it sets the file format to one of the values ​​of the text enumerator:

    XlFileFormat.xlTextMac
    XlFileFormat.xlTextMSDOS
    XlFileFormat.xlTextPrinter
    XlFileFormat.xlTextWindows

Excel ( ):

    XlFileFormat.xlExcel12
    XlFileFormat.xlExcel7
    XlFileFormat.xlExcel8
    XlFileFormat.xlExcel9795

, "or" , :

    bool validFile = ( f == XlFileFormat.xlExcel12   ) 
                  || ( f == XlFileFormat.xlExcel7    ) 
                  || ( f == XlFileFormat.xlExcel8    ) 
                  || ( f == XlFileFormat.xlExcel9795 );

. , , .

+8

. , .

int countBefore = _workbooks.get_Count();
_workbooks.Open(filename);
int countAfter = _workbooks.get_Count();
if (countBefore == countAfter) {
    // The file failed to load.
}
+3

All Articles