getting the row and column numbers from coordinate value in openpyxl

前端 未结 5 1552
情深已故
情深已故 2020-12-07 20:55

I\'m trying to covert a coordinate value in excel to a row number and column number in openpyxl.

For example if my cell coordinate is D4 I want to find the correspon

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-07 21:20

    Old topic, but the answer is not correct!

    dylnmc method was a good one, but has some errors. The calculated row for cell coords like "AA1" or "AAB1" is not correct.

    Below is the corrected version as a function.

    NOTE: This function returns the real coordinated. If you want to use it for example in ExcelWriter, both ROW and COL should be deducted by one. So replace the last line with return(row-1,col-1)

    For example 'AA1' is [1,27] and 'AAA1' is [1,703]; but the python must have them as [0,26] and [0,702].

    import re
    
    def coord2num(coord):
        cell = coord.lower()
    
        # generate matched object via regex (groups grouped by parentheses)
        m = re.match('([a-z]+)([0-9]+)', cell)
    
        if m is None:
            print('Invalid cell: {}'.format(cell))
            return [None,None]
        else:
            col = 0
            for i,ch in enumerate(m.group(1)[::-1]):
                n = ord(ch)-96
                col+=(26**i)*(n)
    
            row = int(m.group(2))
    
        return[row,col]
    

提交回复
热议问题