Home » excel » c# – How do you read the binary data of an Excel file (.xls) using .NET?

c# – How do you read the binary data of an Excel file (.xls) using .NET?

Posted by: admin May 14, 2020 Leave a comment

Questions:

No, ADO.NET will not solve my problem because the excel files I’m working with do not contain information in tabular form. In other words, there is nothing to query, and the name of the sheets and number of sheets will vary.

essentially my job is to search every single cell in an excel document and validate it against some other data.

Right now all I have is a byte[] array that represents the contents of an .xls file. Converting to a string is meaningless since it’s just binary data.

If I use COM interop and run Excel in the background, is it possible to inject it with binary data in byte[] array form or do I have to save the file to disk and then automate the process of opening it and scanning each row?

Isn’t there an easier way to do it?

How to&Answers:

How do you read the binary data of an excel file (.xls) using .NET
There are a number of ways, the excel file format has changed a few times so reading the files natively is hard work and version dependent, it’s usually not recommended. For reading tabular data most people choose ADO.NET, but as you allude, if you need any formatting or discovery then MS would recommend COM Interop.

If I use COM interop and run Excel in the background, is it possible to inject it with binary data in byte[] array form

The excel COM object model does allow you to bulk set data to a Range object you set it with a 2 dimensional object array (object[,])

or do I have to save the file to disk and then automate the process of opening it and scanning each row?

No, you can interact with the “out of process” COM server (Excel) without having to save first, you can set your data, format it etc in memory.

Isn’t there an easier way to do it?
Yes there is, checkout Spreadsheet Gear their object model is nearly identical to the com model, however you do not need Excel involved at all, it is also an order of magnitude faster working with large data. Its not cheap ($1000 bucks last time I checked) but will save you way more than that in coding effort. (I am not affiliated with Spreadsheet gear in any way)

Answer:

You could use NPOI to open & read your XLS files, you’ll basically want to loop through your Sheets / Rows / Columns looking for data. I commonly use NPOI to read & write XLS forms that contain data in random cells throughout a worksheet.