Excel C# interop - obtaining values from cells

Working with C# and Excel has been discussed on this site before with tips on preventing Excel.exe from hanging and converting integers into Excel column headings. Today's post is a very brief example on how we can extract data from specific cells of an Excel worksheet.

Obtaining a value from a specific cell

Assuming we have a value in cell B16 that we wish to have out as a string in our C# code, we can use the following code:

Where:

  • Range comes from the Excel interop namespace ('Microsoft.Office.Interop')
  • worksheet refers to the Excel worksheet you're working on (see example below)

Obtaining a range of values from a range of cells

Assuming we have values in the range B16 to C20 inclusive, we can create a new range to obtain the values from into an array of objects, like so:

Once you have the array of objects you can then cast them to other data types in the usual manner.

Extended example

Here's a quick example of setting up an Excel application, opening a worksheet and obtaining a value using both of the above methods.

Leave a Reply

Your email address will not be published. Required fields are marked *