获取单元格索引
Contents
[
Hide
]
Excel 的默认视图是 A1 样式引用,每列定义为 A、B、C……,单元格命名为 A1、B2、C3……等等。
您可能想知道该单元格位于哪一行和列。
可能的使用场景
当您只需通过行和列索引操作工作表上的特定数据时,您需要了解该特定单元格的行索引和列索引。 Aspose.Cells 提供此功能,以通过行、列和单元格的名称获取行和列索引。 Aspose.Cells 提供以下属性和方法,帮助您实现目标。
- CellsHelper.CellNameToIndex
- CellsHelper.ColumnIndexToName
- CellsHelper.ColumnNameToIndex
- CellsHelper.RowIndexToName
- CellsHelper.RowNameToIndex
注意:在 Aspose.Cells for .Net 中,索引从零开始,但在 MS Excel 中,行的 id 从一开始。
使用 Aspose.Cells 获取单元格索引
此示例演示如何:
- 创建一个工作簿并添加一些数据。
- 在第一个工作表中查找特定单元格。
- 通过单元格名称获取行索引和列索引。
- 通过列名获取列索引。
- 通过行名获取行索引。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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); |