Get the Column Index of a Cell in Excel using OpenXML C#

前端 未结 8 1836
北恋
北恋 2020-12-03 17:32

I\'ve been looking around for a while now and cannot seem to find out how to do this. I\'ve got an excel sheet, which I\'m reading using OpenXML. Now the normal thing would

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-03 18:12

    In my scenario I only needed to deal with column names (no cell numbers), and used LINQ, thought it's worth putting here for the reference.

    const int AsciiTrim = 'A' - 1; //64
    const int LastChar = 'Z' - AsciiTrim; //26
    
    var colIndex = columnName
        .Reverse()
        .Select(ch => ch - AsciiTrim)
        .Select((ch, i) => ch * Math.Pow(LastChar, i))
        .Sum()
        - 1; //make zero-index based
    

    To revert back, and for the full code and test, see this gist.

提交回复
热议问题