How to write a cell with multiple columns in xlwt?

Bin Wang picture Bin Wang · Oct 30, 2013 · Viewed 28.2k times · Source

I'd like to write a table like this:

----------------
| Long Cell    |
----------------
| 1    | 2     |
----------------

How to write the cell Long Cell? Thanks.

I've tried to do it like this:

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

But it end up like:

--------------------
| Long Cell |      |
--------------------
| 1         | 2    |
--------------------

Answer

Peter DeGlopper picture Peter DeGlopper · Oct 30, 2013

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 = 0
bottom_row = 0
left_column = 0
right_column = 1
sheet.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.