Mitch
Mitch

Reputation: 389

C# how to determine excel file version

I am using excel data reader, and I've noticed it is not compatible with older excel 5.0/95 workbook files. Is there a way I can get the version of the .xls file before I send it into excel data reader to prevent sending in earlier versions of excel files?

here is what I am using now.

if (extension == ".XLS")
                    {
                        IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
                        excelReader.IsFirstRowAsColumnNames = true;
                        result = excelReader.AsDataSet();
                    }
                    else
                    {
                        IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
                        excelReader.IsFirstRowAsColumnNames = true;
                        result = excelReader.AsDataSet();
                    }

Upvotes: 2

Views: 2080

Answers (2)

Mr. Mascaro
Mr. Mascaro

Reputation: 2733

There should be a string in the last line of an old excel file that specifies which version of Excel created it. I forget the exact wording for those really old ones, but for Excel 2003 it was "Microsoft Excel 2003 Worksheet"

Upvotes: 0

Donal
Donal

Reputation: 32713

What you have is correct. But you could make it a bit cleaner. For example:

IExcelDataReader excelReader;

if (String.Compare(extension, ".xls", true) == 0){
    excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
} else if (String.Compare(extension , ".xlsx", true) == 0){
    excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}

excelReader.IsFirstRowAsColumnNames = true;
result = excelReader.AsDataSet();

Upvotes: 1

Related Questions