Access Worksheet Cell

Accessing Cells in a Worksheet

Each worksheet contains a property by the name of Cells that is actually a collection of GridCell objects where a GridCell object represents a cell in Aspose.Cells.GridWeb. It is possible to access any cell using Aspose.Cells.GridWeb. There are two preferred methods, each of which is discussed below.

Using Cell Name

All cells have a unique name. For example, A1, A2, B1, B2 etc. Aspose.Cells.GridWeb allows developers to access any desired cell by using the cell name. Simply pass the cell name (as an index) to the Cells collection of the GridWorksheet.

Notice

Accessing a GridCell using cells[cellName] may consume more memory. It will always create a new cell (GridCell) object regardless of whether the cell is null.

Using Row & Column Indices

A cell can also be recognized by its location in terms of row and column indices. Just pass a cell’s row and column indices to the Cells collection of the GridWorksheet. This approach is faster than the above one.

Best Practices:

If we want to get the cell value or cell style and do not want to perform an update operation, we can use CheckCell method, which will return null if the cell does not exist. This will save memory.

   GridCells cells = GridWeb1.ActiveSheet.Cells;
   GridCell cell = cells.CheckCell(1, 1);
   if(cell!=null)
   {
    Console.WriteLine(cell.ToString());
   }

Best Practices:

Iterate over the cells

If we want to access all the cells in the worksheet one by one, we can use iterators to traverse the existing cells. This will save memory.

   GridCells cells = GridWeb1.ActiveSheet.Cells;
   foreach (GridCell c in cells)
  {
      Console.WriteLine(c.ToString());
   }

Compare the code below, which is bad, as it creates all the cell objects regardless of whether they are null, thus causing memory issues, so please do not use this way:

 GridCells cells = GridWeb1.ActiveSheet.Cells;
 for(int r=0;r< cells.MaxRow;r++)
 {
     for(int c=0;c< cells.MaxColumn; c++)
     {
         Console.WriteLine(cells[r,c].ToString());
     }
 }