获取单元格索引

可能的使用场景

当您只需通过行和列索引操作工作表上的特定数据时,您需要了解该特定单元格的行索引和列索引。 Aspose.Cells 提供此功能,以通过行、列和单元格的名称获取行和列索引。 Aspose.Cells 提供以下属性和方法,帮助您实现目标。

注意:在 Aspose.Cells for .Net 中,索引从零开始,但在 MS Excel 中,行的 id 从一开始。

使用 Aspose.Cells 获取单元格索引

此示例演示如何:

  1. 创建一个工作簿并添加一些数据。
  2. 在第一个工作表中查找特定单元格。
  3. 通过单元格名称获取行索引和列索引。
  4. 通过列名获取列索引。
  5. 通过行名获取行索引。
//Instantiating an Workbook object
Workbook workbook = new Workbook();
//Obtaining the reference of the newly added worksheet
Worksheet ws = workbook.Worksheets[0];
Cells cells = ws.Cells;
//Setting the value to the cells
Cell cell = cells["A1"];
cell.PutValue("Fruit");
cell = cells["B1"];
cell.PutValue("Count");
cell = cells["C1"];
cell.PutValue("Price");
cell = cells["A2"];
cell.PutValue("Apple");
cell = cells["A3"];
cell.PutValue("Mango");
cell = cells["A4"];
cell.PutValue("Blackberry");
cell = cells["A5"];
cell.PutValue("Cherry");
cell = cells["B2"];
cell.PutValue(5);
cell = cells["B3"];
cell.PutValue(3);
cell = cells["B4"];
cell.PutValue(6);
cell = cells["B5"];
cell.PutValue(4);
cell = cells["C2"];
cell.PutValue(5);
cell = cells["C3"];
cell.PutValue(20);
cell = cells["C4"];
cell.PutValue(30);
cell = cells["C5"];
cell.PutValue(60);
Cell curr = cells.Find("Blackberry", null);
int currRow;
int currCol;
//get row and column index of current cell
CellsHelper.CellNameToIndex(curr.Name, out currRow, out currCol);
Console.WriteLine("Row Index: " + currRow + " Column Index: " + currCol);
//get column name by column index
string columnName = CellsHelper.ColumnIndexToName(currCol);
//get row name by row index
string rowName = CellsHelper.RowIndexToName(currRow);
Console.WriteLine("Column Name: " + columnName + " Row Name: " + rowName);
//get column index by column name
int columnIndex = CellsHelper.ColumnNameToIndex(columnName);
//get row index by row name
int rowIndex = CellsHelper.RowNameToIndex(rowName);
Console.WriteLine("Column Index: " + columnIndex + " Row Index: " + rowIndex);
Assert.AreEqual(columnIndex, currCol);
Assert.AreEqual(rowIndex, currRow);