How to get value present in a merged cell?

后端 未结 5 397
星月不相逢
星月不相逢 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:53

    As soon as the only answer is incorrect (there is no more cells_from_range function in openpyxl) I suggest alternative way. I tried and it worked for my case:

    Input is sheet and Cell. But if you need, it can be easily modified to accept string cell representation like 'A3'.

    import openpyxl
    
    
    def getValueWithMergeLookup(sheet, cell):
        idx = cell.coordinate
        for range_ in sheet.merged_cell_ranges:
            merged_cells = list(openpyxl.utils.rows_from_range(range_))
            for row in merged_cells:
                if idx in row:
                    # If this is a merged cell,
                    # return  the first cell of the merge range
                    return sheet.cell(merged_cells[0][0]).value
    
        return sheet.cell(idx).value
    

提交回复
热议问题