将 A 转换为 1 B 转换为 2 ... Z 转换为 26,然后将 AA 转换为 27 AB 转换为 28(Excel 中列引用的列索引) [英] Convert A to 1 B to 2 ... Z to 26 and then AA to 27 AB to 28 (column indexes to column references in Excel)

查看:24
本文介绍了将 A 转换为 1 B 转换为 2 ... Z 转换为 26,然后将 AA 转换为 27 AB 转换为 28(Excel 中列引用的列索引)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人有算法或逻辑将 A 转换为 1,B 转换为 2,...,Z 转换为 26,然后,AA 转换为 27,AB 转换为 28 等等.

Does any one have algorithm or logic to Convert A to 1 ,B to 2, ... ,Z to 26 and then ,AA to 27, AB to 28 etc.

换句话说,将列索引转换为 Excel 中的列引用.

In other words, converting a column index into the column reference in Excel.

推荐答案

看看这些

/// <summary>
/// 1 -> A<br/>
/// 2 -> B<br/>
/// 3 -> C<br/>
/// ...
/// </summary>
/// <param name="column"></param>
/// <returns></returns>
public static string ExcelColumnFromNumber(int column)
{
    string columnString = "";
    decimal columnNumber = column;
    while (columnNumber > 0)
    {
        decimal currentLetterNumber = (columnNumber - 1) % 26;
        char currentLetter = (char)(currentLetterNumber + 65);
        columnString = currentLetter + columnString;
        columnNumber = (columnNumber - (currentLetterNumber + 1)) / 26;
    }
    return columnString;
}

/// <summary>
/// A -> 1<br/>
/// B -> 2<br/>
/// C -> 3<br/>
/// ...
/// </summary>
/// <param name="column"></param>
/// <returns></returns>
public static int NumberFromExcelColumn(string column)
{
    int retVal = 0;
    string col = column.ToUpper();
    for (int iChar = col.Length - 1; iChar >= 0; iChar--)
    {
        char colPiece = col[iChar];
        int colNum = colPiece - 64;
        retVal = retVal + colNum * (int)Math.Pow(26, col.Length - (iChar + 1));
    }
    return retVal;
}

这篇关于将 A 转换为 1 B 转换为 2 ... Z 转换为 26,然后将 AA 转换为 27 AB 转换为 28(Excel 中列引用的列索引)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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