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

前端 未结 8 1801
北恋
北恋 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.

    0 讨论(0)
  • 2020-12-03 18:21

    To start answer , I invite you to look at this first.

    As I have explained there is NO easy way to extract Row and Column. The closest you get is the extraction of CellReference of a cell which would have the form of A1 , B2 which is actualy COLUMN_ROW format.

    What you can do is extract Row and Column from the CellReference. Yes this would need you to implement a method where you need to check char by charto verify for numbers and strings.

    Lets say you have A11 , then when you need to index column you need to extract A which would give as column 1. Yes it's not that easy, but it's the only way unless you simply chose to count the columns when you scan/iterate through cells.

    Again look at this questions answer which does the same thing.

    0 讨论(0)
提交回复
热议问题