将 Excel 列字母转换为其数字的算法是什么? [英] What is the algorithm to convert an Excel Column Letter into its Number?

查看:50
本文介绍了将 Excel 列字母转换为其数字的算法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种算法来将 Excel Column 字母转换为其正确的数字.

I need an algorithm to convert an Excel Column letter to its proper number.

这将用 C# 编写的语言,但任何语言都可以,甚至是伪代码.

The language this will be written in is C#, but any would do or even pseudo code.

请注意,我将把它放在 C# 中,我不想使用 office dll.

Please note I am going to put this in C# and I don't want to use the office dll.

对于A",预期结果将为 1

For 'A' the expected result will be 1

对于 'AH' = 34

For 'AH' = 34

对于 'XFD' = 16384

For 'XFD' = 16384

推荐答案

public static int ExcelColumnNameToNumber(string columnName)
{
    if (string.IsNullOrEmpty(columnName)) throw new ArgumentNullException("columnName");

    columnName = columnName.ToUpperInvariant();

    int sum = 0;

    for (int i = 0; i < columnName.Length; i++)
    {
        sum *= 26;
        sum += (columnName[i] - 'A' + 1);
    }

    return sum;
}

这篇关于将 Excel 列字母转换为其数字的算法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆