How to get value present in a merged cell?

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

    from openpyxl import cell as xlcell, worksheet
    def within_range(bounds: tuple, cell: xlcell) -> bool:
        column_start, row_start, column_end, row_end = bounds
        row = cell.row
        if row >= row_start and row <= row_end:
            column = cell.column
            if column >= column_start and column <= column_end:
                return True
        return False
    
    def get_value_merged(sheet: worksheet, cell: xlcell) -> any:
        for merged in sheet.merged_cells:
            if within_range(merged.bounds, cell):
                return sheet.cell(merged.min_row, merged.min_col).value
        return cell.value
    

    Should do it for current openpyxl version (2.6.3)

提交回复
热议问题