48 lines
1.4 KiB
C#
48 lines
1.4 KiB
C#
namespace QWERTYkez.ExcelProcessor;
|
|
|
|
internal static class CellAddressHelper
|
|
{
|
|
private const string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|
private static readonly uint[] _powers = [1, 26, 676];
|
|
|
|
public static uint ColumnLetterToIndex(string col)
|
|
{
|
|
uint index = 0;
|
|
foreach (char ch in col)
|
|
{
|
|
char c = char.ToUpperInvariant(ch);
|
|
if (c < 'A' || c > 'Z') return 0;
|
|
index = index * 26 + (uint)(c - 'A' + 1);
|
|
}
|
|
return index;
|
|
}
|
|
|
|
public static string ColumnIndexToLetter(uint col)
|
|
{
|
|
if (col == 0) return "";
|
|
uint n = col;
|
|
char[] buf = new char[3];
|
|
int idx = 0;
|
|
while (n > 0)
|
|
{
|
|
n--;
|
|
buf[idx++] = (char)('A' + (n % 26));
|
|
n /= 26;
|
|
}
|
|
return new string(buf, 0, idx);
|
|
}
|
|
|
|
public static bool TryParseCellReference(string reference, out uint row, out uint col)
|
|
{
|
|
row = 0; col = 0;
|
|
if (string.IsNullOrEmpty(reference)) return false;
|
|
int i = 0;
|
|
while (i < reference.Length && char.IsLetter(reference[i])) i++;
|
|
if (i == 0) return false;
|
|
string colPart = reference.Substring(0, i);
|
|
string rowPart = reference.Substring(i);
|
|
if (!uint.TryParse(rowPart, out row)) return false;
|
|
col = CellAddressHelper.ColumnLetterToIndex(colPart);
|
|
return true;
|
|
}
|
|
} |