【问题标题】:How to get column index in Excel using excel-column-name format in C#如何在 C# 中使用 excel-column-name 格式在 Excel 中获取列索引
【发布时间】:2013-07-10 20:49:09
【问题描述】:

我在这里找到了 http://lateral8.com/articles/2010/3/5/openxml-sdk-20-export-a-datatable-to-excel.aspx 很棒的功能

private string getColumnName(int columnIndex)
{
    int dividend = columnIndex;
    string columnName = String.Empty;
    int modifier;

    while (dividend > 0)
    {
        modifier = (dividend - 1) % 26;
        columnName = 
            Convert.ToChar(65 + modifier).ToString() + columnName;
        dividend = (int)((dividend - modifier) / 26);
    }

    return columnName;
}

我想做类似的事情 - 提供列名并接收索引。例如,提供名称“AB”并作为结果索引接收 28。如何做到这一点?

更新:

令人惊讶的是,我在 cmets 部分找到了解决方案

这里 https://stackoverflow.com/a/8739121/907732

这里 https://stackoverflow.com/a/4888750/907732

【问题讨论】:

标签: c# excel


【解决方案1】:
public static string GetColumnName(int index)
{
    const string letters = "ZABCDEFGHIJKLMNOPQRSTUVWXY";

    int NextPos = (index / 26);
    int LastPos = (index % 26);
    if (LastPos == 0) NextPos--;

    if (index > 26)
        return GetColumnName(NextPos) + letters[LastPos];
    else
        return letters[LastPos] + "";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-27
    • 2023-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多