Excel标题与索引的对应关系

时间:2021-05-27 22:14:10
/// <summary>
/// 返回对应标题的索引
/// </summary>
/// <param name="columnTitle">Excel定义列标题:大写字母</param>
/// <returns>索引从0开始</returns>
public static int GetColumnIndex(string columnTitle)
{
int len = columnTitle.Length - ;
int index = ;
for (int i = len; i >=; i--)
{
index += GetColumnTitleNumber(columnTitle[i])*Convert.ToInt32(Math.Pow(, len - i));
}
return --index;
} private static int GetColumnTitleNumber(char columnTitle)
{
int startNumber = Convert.ToInt32('A');
int currentNumber = Convert.ToInt32(columnTitle);
if (currentNumber < startNumber || currentNumber >= startNumber + )
throw new ArgumentOutOfRangeException(columnTitle+"列标题超出定义");
return Convert.ToInt32(columnTitle) - startNumber + ;
} /// <summary>
/// 根据列的索引返回对应的标题
/// </summary>
/// <param name="columnIndex">列索引从0开始</param>
/// <returns></returns>
public static string GetColumnTitle(int columnIndex)
{
int columnNumber = columnIndex + ;
int left = columnNumber/;
int startNumber = Convert.ToInt32('A');
if (left == || (left == && (columnNumber% == )))
{
return ((char) (startNumber + columnNumber - )).ToString();
}
if (columnNumber% == )
left--;
return GetColumnTitle(left) + GetColumnTitle(columnNumber - left * );
}