如何在xlwt中编写多列的单元格?

Bin*_*ang 23 python excel xlwt

我想写一个这样的表:

----------------
| Long Cell    |
----------------
| 1    | 2     |
----------------
Run Code Online (Sandbox Code Playgroud)

怎么写单元格Long Cell?谢谢.

我试过这样做:

sheet.write(0, 0, 'Long Cell')
sheet.write(1, 0, 1)
sheet.write(1, 1, 2)
Run Code Online (Sandbox Code Playgroud)

但最终结果如下:

--------------------
| Long Cell |      |
--------------------
| 1         | 2    |
--------------------
Run Code Online (Sandbox Code Playgroud)

Pet*_*per 55

据我所知,这没有记录 - 您必须阅读源代码才能找到它.有两种方法的Worksheet类来做到这一点,write_mergemerge.merge获取现有单元格并合并它们,同时write_merge写入标签(就像write),然后做同样的事情merge.

两者都将单元格合并为r1, r2, c1, c2,并接受可选style参数.

从您的示例中,这将是最简单的调用:

sheet.write_merge(0, 0, 0, 1, 'Long Cell')
sheet.write(1, 0, 1)
sheet.write(1, 1, 2)
Run Code Online (Sandbox Code Playgroud)

更清楚地了解呼叫的工作原理:

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')
Run Code Online (Sandbox Code Playgroud)

或者,使用merge:

sheet.write(top_row, left_column, 'Long Cell')
sheet.merge(top_row, bottom_row, left_column, right_column)
Run Code Online (Sandbox Code Playgroud)

merge 在消息来源中有一些评论指出了潜在的问题:

    # 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.
Run Code Online (Sandbox Code Playgroud)

但对于像这样的简单案例来说,这样会很好.