How to get value present in a merged cell?

后端 未结 5 398
星月不相逢
星月不相逢 2021-01-12 19:58

I want to get value of a merged cell that has range from D3 to H3 using openpyxl library. As per my understanding most libraries read data from 1st cell itself. Thus the mer

5条回答
  •  太阳男子
    2021-01-12 20:38

    Here's an approximation of the function that I use for this:

    from openpyxl.cell import get_column_letter
    from openpyxl.worksheet import cells_from_range
    
    def getValueWithMergeLookup(sheet, col, row):
        idx = '{0}{1}'.format(get_column_letter(col), row)
        for range_ in sheet.merged_cell_ranges:
            cells = list(cells_from_range(range_))[0]
            if idx in cells:
                # If this is a merged cell, you can look up the value 
                # in the first cell of the merge range
                return sheet.cell(cells[0]).value
    
        return sheet.cell(row=row, column=col).value
    

    The only really dicey bit there is where I extract the list of cells within the range to search against. That returns a generator, so I cast it to a list (because in doesn't work on generators, apparently), which yields a tuple containing a single list element, which I extract using the 0-index.

    For my purposes, this is fast enough -- I use it by iterating the cells I want to test. If you wanted to make this more performant, it might be worthwhile to invert the loop, iterating the merge ranges as your outer loop, so you only have to do that conversion once.

提交回复
热议问题