How to write a cell with multiple columns in xlwt? How to write a cell with multiple columns in xlwt? python python

How to write a cell with multiple columns in xlwt?


As far as I can tell, this isn't documented - you have to read the source code to find it. There are two methods on the Worksheet class to do this, write_merge and merge. merge takes existing cells and merges them, while write_merge writes a label (just like write) and then does the same stuff merge does.

Both take the cells to merge as r1, r2, c1, c2, and accept an optional style parameter.

From your example, this would be the simplest call:

sheet.write_merge(0, 0, 0, 1, 'Long Cell')sheet.write(1, 0, 1)sheet.write(1, 1, 2)

To be more explicit about how the call works:

top_row = 0bottom_row = 0left_column = 0right_column = 1sheet.write_merge(top_row, bottom_row, left_column, right_column, 'Long Cell')

Alternatively, using merge:

sheet.write(top_row, left_column, 'Long Cell')sheet.merge(top_row, bottom_row, left_column, right_column)

merge has some comments in the source pointing out potential problems:

    # Problems: (1) style to be used should be existing style of    # the top-left cell, not an arg.    # (2) should ensure that any previous data value in    # non-top-left cells is nobbled.    # Note: if a cell is set by a data record then later    # is referenced by a [MUL]BLANK record, Excel will blank    # out the cell on the screen, but OOo & Gnu will not    # blank it out. Need to do something better than writing    # multiple records. In the meantime, avoid this method and use    # write_merge() instead.

But it would be fine for a simple case like this.