python - 如何在 xlwt 中编写具有多列的单元格?

标签 python excel xlwt

我想写一个这样的表格:

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

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

我试过这样做:

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

但结果是这样的:

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

最佳答案

据我所知,这没有记录 - 您必须阅读源代码才能找到它。 Worksheet 类有两种方法可以做到这一点,write_mergemergemerge 获取现有单元格并将它们合并,而 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)

更明确地说明调用的工作原理:

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')

或者,使用 merge:

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

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.

但对于这样一个简单的案例来说,它会很好。

关于python - 如何在 xlwt 中编写具有多列的单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19672760/

相关文章:

python - 带有 LXML 元素的 XPath

python "IndexError: list index out of range"|目标 : Read 1 excel file & append data to a 2nd excel file

python - Pandas:将行追加到已经通过 pandas.DataFrame.apply 运行的 DataFrame

Python:如何使用 matplotlib 在 python 中绘制条形图?

excel - ListObject 表行数

vba - 范围链接到相邻列中的最后一个单元格

python - 使用 easyxf 在 xlwt 中进行文本对齐

python - 如何使用 python xlrd 从 excel 工作表中检索图像

python - Python3 的 pathlib 可以在 Linux 和 Windows 系统之间移植使用吗?

vb.net - 用户完成后关闭 Excel