Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to verify if a file is a valid excel spreadsheet?

I already did some search here on SO, on this, this, this and more, but no clue, so I'm going to have to ask you guys.

I'm trying to open an Excel file via Interop, and I have Office 2007 installed, so I'm using Microsoft.Office.Interop.Excel version 14.0.

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

But if I try to open an invalid file (like a bitmap, or an executable) via Interop, Excel opens it without complain or warning.

How can I detect Excel has an invalid workbook file loaded, without blocking with an alert ?

I'm trying to write a unit test of my Excel object reader. One of the cases is to try to open an invalid file.

Some code to help: Application Creation:

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

Workbook opening:

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

EDIT: Just to add 1 more information: Excel loads the invalid file. If DisplayAlerts is set to true, it complains (open a dialog) informing the workbook seems to be corrupted, but if DisplayAlerts is set to false, it loads the file just as below:

Excel Loads Invalid File

like image 411
Machado Avatar asked Jan 17 '12 21:01

Machado


2 Answers

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

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

And inside this enumeration Excel has the valid files (valid for my purpose):

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

So I ended using a simple "or" to filter the kind of file I'd like to import:

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

And now it works. Thanks for your help guys, you set me in the right direction.

like image 113
Machado Avatar answered Sep 28 '22 23:09

Machado


You can check the workbook count before and after loading the file. If both counts are the same, the file failed to load.

int countBefore = _workbooks.get_Count();
_workbooks.Open(filename);
int countAfter = _workbooks.get_Count();
if (countBefore == countAfter) {
    // The file failed to load.
}
like image 43
Frédéric Hamidi Avatar answered Sep 29 '22 01:09

Frédéric Hamidi