Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the Excel Cell value by address (A1, A2) using NPOI

Tags:

c#

npoi

I have an Excel Cell Address like A1, A2. How do I access this cell programmatically using NPOI framework in C#?

Some Java POI example code I found:

CellReference cr = new CellReference("A1"); 
row = mySheet.getRow(cr.getRow()); 
cell = row.getCell(cr.getCol());
like image 356
Anand K G Avatar asked Jun 03 '16 07:06

Anand K G


People also ask

How do I find the cell address in Apache POI?

Use CellAddress when you want to refer to the location of a cell in a sheet when the concept of relative/absolute does not apply (such as the anchor location of a cell comment). Use CellReference when the concept of relative/absolute does apply (such as a cell reference in a formula).


1 Answers

The Java code you found translates 1:1 into C#:

  • First you convert the cell description (A1) into a CellReference
  • Use the Row and Col from that CellReference to lookup the actual cell.

Here is some sample code

var workbook = new XSSFWorkbook(stream);
var sheet = workbook.GetSheetAt(0);

var cr = new CellReference("D5");
var row = sheet.GetRow(cr.Row);
var cell = row.GetCell(cr.Col);

Console.Write(cell.StringCellValue);

Do note that referencing an empty Cell will result in an exception. Excel doesn't store non-used cells internally, and (N)POI does not attempt to hide that fact from the developer.

like image 110
Paul-Jan Avatar answered Sep 22 '22 14:09

Paul-Jan