Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何简化列数到列Alpha表示函数?_C#_Excel Interop_Alphabetical_Alphanumeric - Fatal编程技术网

C# 如何简化列数到列Alpha表示函数?

C# 如何简化列数到列Alpha表示函数?,c#,excel-interop,alphabetical,alphanumeric,C#,Excel Interop,Alphabetical,Alphanumeric,我有一个遗留代码: private Worksheet _xlSheet; . . . _xlSheet.PageSetup.PrintArea = "A1:" + GetExcelTextColumnName(_grandTotalsColumn) + finalRow; . . . protected string GetExcelTextColumnName(int columnNum) { StringBuilder sb = new StringBuilder();

我有一个遗留代码:

private Worksheet _xlSheet;
. . .
_xlSheet.PageSetup.PrintArea = "A1:" +
    GetExcelTextColumnName(_grandTotalsColumn) + finalRow;
. . .
protected string GetExcelTextColumnName(int columnNum)
{
    StringBuilder sb = new StringBuilder();
    if (columnNum > 26)
    {
        int firstLetter = ((columnNum - 1) / 26) + 64;
        int secondLetter = ((columnNum - 1) % 26) + 65;
        sb.Append((char)firstLetter);
        sb.Append((char)secondLetter);
    }
    else
    {
        sb.Append((char)(64 + (columnNum - 1)));
    }
    return sb.ToString();
}
我将代码简化到这样的程度:

_xlSheet.PageSetup.PrintArea = "A1:" + GetExcelTextColumnName(_xlSheet.UsedRange.Columns.Count) + _xlSheet.UsedRange.Rows.Count;

…但想知道是否有办法简化“列编号到列Alpha”的代码。是否存在,或者现有的GetExcelTextColumnName()是否真的优雅、简洁且可维护?我将使用迭代算法,它将支持ZZ以外的列,而ZZ是您在最新版本的Excel中找到的

   private const string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public string GetColumnName(int columnIndex)
    {
        if (columnIndex < 0) throw new ArgumentOutOfRangeException("columnIndex", columnIndex, "Column index index may not be negative.");
        string result = "";
        for (; ; )
        {
            result = Alphabet[(columnIndex) % 26] + result;
            if (columnIndex < 26) break;
            columnIndex = columnIndex / 26 - 1;
        }
        return result;
    }

这是递归算法的完美例子;我所做的唯一更改是将“const”更改为“static readonly”
_xlSheet.PageSetup.PrintArea = 
    _xlSheet.Range("A1")
    .Resize(finalRow, _grandTotalsColumn).Address;