Search code examples
pythonexcelxlrd

End of merged cells in Excel with Python


I am using xlrd package to parse Excel spreadsheets. I would like to get the end index of a merged cell.

  A   B   C
  +---+---+----+
1 | 2 | 2 | 2  |
  +   +---+----+
2 |   | 7 | 8  |
  +   +---+----+
3 |   | 0 | 3  |
  +   +---+----+
4 |   | 4 | 20 |
  +---+---+----+
5 |   | 2 | 0  |
  +---+---+----+

given the row index and the column index, I would like to know the end index of the merged cell (if merged)

in this example for (row,col)=(0,0) ; end = 3


Solution

  • You can use merged_cells attribute of the Sheet object: https://secure.simplistix.co.uk/svn/xlrd/trunk/xlrd/doc/xlrd.html?p=4966#sheet.Sheet.merged_cells-attribute

    It returns the list of address ranges of cells which have been merged.

    If you want to get end index only for the vertically merged cells:

    def is_merged(row, column):
        for cell_range in sheet.merged_cells:
            row_low, row_high, column_low, column_high = cell_range
            if row in xrange(row_low, row_high) and column in xrange(column_low, column_high):
                return (True, row_high-1)
        return False