简体   繁体   English

使用C#在Excel / VSTO中的列号为列号

[英]Column No to Column Letter in Excel/VSTO using C#

How to find column's name or header? 如何查找列的名称或标题?

For example if i select column 5 in excel means i want the result as "E". 例如,如果我在Excel中选择第5列意味着我希望结果为“E”。 How to get the alphabet or letter corresponding to column no. 如何获取对应于列号的字母或字母。

Please help me with the code 请帮我解释一下代码

public static string GetColumnName(int columnNumber)
{
    const string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    string columnName = "";

    while (columnNumber > 0)
    {
        columnName = letters[(columnNumber - 1) % 26] + columnName;
        columnNumber = (columnNumber - 1) / 26;
    }

    return columnName;
}

What about using Application.ActiveCell.get_Address(true, true, Excel.AlReferenceStyle.xlA1, missing, missing) and then parse the result string or use a RegEx to get the column heading? 如何使用Application.ActiveCell.get_Address(true, true, Excel.AlReferenceStyle.xlA1, missing, missing) ,然后解析结果字符串或使用RegEx获取列标题?

I simply used: 我只是用过:

string location = Application.ActiveCell.get_Address(true, true, Excel.AlReferenceStyle.xlA1, missing, missing);
string tokens = x.Split("$".ToCharArray());
MessageBox.Show(String.Format("Column {0}", result[0]));
public static long GetColumnNumber(string columnName)
{
    int letterPos = 0;   
    long columnNumber = 0;
    for (int placeHolder = columnName.Length - 1; placeHolder >= 0; placeHolder--)
    {
        int currentSum = 1;
        for (int multiplier = 0; multiplier < placeHolder; multiplier++)
            currentSum *= 26;
        int letterValue = (int) columnName[letterPos];
        currentSum *= letterValue - 64;
        columnNumber += currentSum;
        if (letterPos != columnName.Length)
            letterPos++;
        //Console.WriteLine(((int)columnName[i]-64) + " = " + columnName[i]);
    }
        return columnNumber;
}

I use these two: 我用这两个:

public string GetExcelColumn(int index)
{
    int quotient = index / 26;

    if (quotient > 0)
        return GetExcelColumn(quotient - 1) + (char)((int)'A' + (index % 26));
    else
        return "" + (char)((int)'A' + index);
}

static IEnumerable<string> GetExcelColumns()
{
    var alphabet = new string[]{""}.Union(from c in Enumerable.Range((int)'A', 26) select Convert.ToString((char)c));

    return from c1 in alphabet
            from c2 in alphabet
            from c3 in alphabet.Skip(1)                    // c3 is never empty
            where c1 == string.Empty || c2 != string.Empty // only allow c2 to be empty if c1 is also empty
            select c1 + c2 + c3;
}

The following is a complete method which gives you the corresponding alphabet for an integer value that is passed. 以下是一个完整的方法,它为您传递的整数值提供相应的字母表。

private String Number2String(int number, bool isCaps)
    {
        int number1 = number / 27;
        int number2 = number - (number1 * 26);
        if (number2 > 26)
        {
            number1 = number1 + 1;
            number2 = number - (number1 * 26);
        }
        Char a = (Char)((isCaps ? 65 : 97) + (number1 - 1));
        Char b = (Char)((isCaps ? 65 : 97) + (number2 - 1));
        Char c = (Char)((isCaps ? 65 : 97) + (number - 1));
        string d = String.Concat(a, b);
        if (number <= 26)
            return c.ToString();
        else
            return d;
    }

This works well in VBA by using a double replace, where R is a Single Cell Excel Range: 这在VBA中通过使用双重替换很有效,其中R是单个单元格Excel范围:

ColumnLetter = Replace(Replace(R.AddressLocal(ReferenceStyle:=1), "$", vbNullString), R.Row, vbNullString) It is based on the equivalent idea for use on a Worksheet. ColumnLetter = Replace(Replace(R.AddressLocal(ReferenceStyle:=1), "$", vbNullString), R.Row, vbNullString)它基于在工作表上使用的等效思想。 In a Cell Formula use this, it is even shorter: 在Cell Formula中使用它,它甚至更短:

=SUBSTITUTE(ADDRESS(1,COLUMN(M1),4),1,"")

This returns the letter M and works right up to Column XFD. 这将返回字母M,并一直工作到XFD列。 The cell reference M1 can be any Range anywhere. 单元格引用M1可以是任何范围。 The top left Column is returned for Ranges or more than one cell. 为范围或多个单元格返回左上方的列。

It gets the ADDRESS of the first Cell in the Column and then removes the trailing 1 by substituting a NullString for it. 它获取列中第一个Cell的ADDRESS,然后通过用NullString替换它来删除尾随1。 (The 4 in the ADDRESS makes sure that the Address is returned as a Relative Address, ie one without and $ signs in it.) (ADDRESS中的4确保地址作为相对地址返回,即一个没有和$符号。)

Thanks to barry houdini who set me off on the quest for a good answer to this. 感谢巴里·胡迪尼bary houdini )让我对这个问题给出了很好的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM