使用C++获取单元格索引
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 C++中索引从零开始,但在MS Excel中行的ID是从一开始的。
使用 Aspose.Cells 获取单元格索引
此示例演示如何:
- 创建一个工作簿并添加一些数据。
- 在第一个工作表中查找特定单元格。
- 通过单元格名称获取行索引和列索引。
- 通过列名获取列索引。
- 通过行名获取行索引。
#include <iostream>
#include "Aspose.Cells.h"
using namespace Aspose::Cells;
int main() {
Aspose::Cells::Startup();
// Instantiating a Workbook object
Workbook workbook;
// Obtaining the reference of the newly added worksheet
Worksheet ws = workbook.GetWorksheets().Get(0);
Cells cells = ws.GetCells();
// Setting the value to the cells
Cell cell = cells.Get(u"A1");
cell.PutValue(u"Fruit");
cell = cells.Get(u"B1");
cell.PutValue(u"Count");
cell = cells.Get(u"C1");
cell.PutValue(u"Price");
cell = cells.Get(u"A2");
cell.PutValue(u"Apple");
cell = cells.Get(u"A3");
cell.PutValue(u"Mango");
cell = cells.Get(u"A4");
cell.PutValue(u"Blackberry");
cell = cells.Get(u"A5");
cell.PutValue(u"Cherry");
cell = cells.Get(u"B2");
cell.PutValue(5);
cell = cells.Get(u"B3");
cell.PutValue(3);
cell = cells.Get(u"B4");
cell.PutValue(6);
cell = cells.Get(u"B5");
cell.PutValue(4);
cell = cells.Get(u"C2");
cell.PutValue(5);
cell = cells.Get(u"C3");
cell.PutValue(20);
cell = cells.Get(u"C4");
cell.PutValue(30);
cell = cells.Get(u"C5");
cell.PutValue(60);
Cell curr = cells.Find(u"Blackberry", nullptr);
int currRow, currCol;
// Get row and column index of current cell
CellsHelper::CellNameToIndex(curr.GetName(), currRow, currCol);
std::cout << "Row Index: " << currRow << " Column Index: " << currCol << std::endl;
// Get column name by column index
U16String columnName = CellsHelper::ColumnIndexToName(currCol);
// Get row name by row index
U16String rowName = CellsHelper::RowIndexToName(currRow);
std::cout << "Column Name: " << columnName.ToUtf8() << " Row Name: " << rowName.ToUtf8() << std::endl;
// Get column index by column name
int columnIndex = CellsHelper::ColumnNameToIndex(columnName);
// Get row index by row name
int rowIndex = CellsHelper::RowNameToIndex(rowName);
std::cout << "Column Index: " << columnIndex << " Row Index: " << rowIndex << std::endl;
// Assertions
if (columnIndex != currCol || rowIndex != currRow) {
std::cerr << "Assertion failed!" << std::endl;
}
Aspose::Cells::Cleanup();
return 0;
}