使用 C# Excel Interop 中的列字母将选定的列值从 Excel 存储到数组

Store selected column value from Excel to an Array using column letters in C# Excel Interop

我正在与 excel 合作,将记录导入到我当前创建的程序中。我通常从 excel 中获取记录并通过列索引将其存储到数组中,如下所示:

Excel.Range xlRange = xlWorksheet.UsedRange;
string[,] arr = new string[rowCount, colCount];

for (int i = 1; i <= rowCount; i++)
{
    for (int j = 1; j <= colCount; j++)
    {
        arr[i, j] = xlRange.Cells[i, j].Value;
    }
}

现在,在我目前的工作中,列索引是未知的。唯一给出的是列名称,例如列 "AP"、"QR" 等。用户将定义他将从哪一列获取数据。

有没有类似arr[i, j] = xlRange.Cells["AP", j].Value;的方法?

注意:

该数组将包含来自两列或更多列的数据,而不仅仅是一列。

我找到了答案 here。通过以下函数将列名转换为范围:

public static int GetColumnNumber(string name)
{
    int number = 0;
    int pow = 1;
    for (int i = name.Length - 1; i >= 0; i--)
    {
         number += (name[i] - 'A' + 1) * pow;
         pow *= 26;
    }  

    return number;
}

将行索引更改为转换后的数字。

arr[i, j] = xlRange.Cells[GetColumnNumber("PA"), j].Value;

我认为 C# 中的 Rangeget_Range 索引器将使用 row/column 或语义单元描述。所以,这些都应该有效:

Excel.Range r = sheet.Range[1, 1];

Excel.Range r = sheet.Range["A1"];

这意味着您甚至可以简单地让 Excel 承担繁重的工作:

public string GetRange(string Column, int Row)
{
    return string.Format("{0}{1}", Column, Row);
}