数字→文字列変換等が必要になるのでメモ。
Range, Cellsのパフォーマンスは以下より
Excel 100×10のデータを取得する方法の比較
Range vs Cells(1セルを取得)
Range vs Cells(範囲を取得)
数字→文字列
public string ToAlphabet(int columnNo)
{
string alphabet = "ZABCDEFGHIJKLMNOPQRSTUVWXY";
string columnStr = string.Empty;
int m = 0;
do
{
m = columnNo % 26;
columnStr = alphabet[m] + columnStr;
columnNo = columnNo / 26;
} while (0 < columnNo && m != 0);
return columnStr;
}
文字列→数字
public string ToAlphabet(int columnNo)
{
columnStr = columnStr.ToUpper();
double result = 0;
for (int i = 0; i < columnStr.Length; i++)
{
int x = columnStr.Length - i - 1;
int num = Convert.ToChar(columnStr[x]) - 64;
result += num * Math.Pow(26, i);
}
return Convert.ToInt32(result);
}
ToAlphabetのループ文とアルゴリズムが間違ってますね
返信削除26の時だけZになるけど52以上の26の倍数は余計にループして2桁目がずれる
正しくは
12行目while (0 < columnNo);にして
ループ文の最後にif (m == 0) { columnNo-= 1; }