编程语言
首页 > 编程语言> > Excel 列名转int索引(C#版)

Excel 列名转int索引(C#版)

作者:互联网

/// <summary>
/// 获取Excel实际列索引
/// </summary>
/// <param name="columnName">Excel列名</param>
/// <returns>int格式索引</returns>
public int GetColumnIndex(string columnName)
{
	int result = 0;
	// A-Z 转换成 0-25的数字,并反转
	int[] colReverse = Encoding.ASCII.GetBytes(columnName.ToUpper()).Select(x =>
	{
		int aIndex = Encoding.ASCII.GetBytes("A")[0];
		int zIndex = Encoding.ASCII.GetBytes("Z")[0];
		return x < aIndex || x > zIndex ? 
            throw new ArgumentException($"参数有误{nameof(columnName)}") : 
        		x - aIndex;
	}).Reverse().ToArray();

    // 当成26进制数,遍历计算
    for (int i = 0; i < colReverse.Count(); i++)
    {
        // 个位(0~25)  其他位(1~26)
        int vReal = colReverse[i] + (i == 0 ? 0 : 1);
        result += vReal * (int)Math.Pow(26, i);
    }
    return result;
}

标签:26,columnName,int,Excel,C#,result,colReverse
来源: https://www.cnblogs.com/wosperry/p/14885189.html