说说如何使用 Python 在 word 中创建表格

我们可以使用 python-docx 模块,实现在 word 中创建表格。

请看下面这段代码:

    table = doc.add_table(rows=1, cols=len(titles))
    # 设置表格样式
    table.style = 'Light List Accent 1'
    # 设置标题
    title_cells = table.rows[0].cells
    for i in range(len(titles)):
        title_cells[i].text = titles[i]

    # 设置内容
    for d in data:
        row_cells = table.add_row().cells
        for i in range(len(titles)):
            row_cells[i].text = d[i]

运行结果:

现在让我们来分析这段代码。

**(1)**首先调用 add_table 方法,创建 Table 对象

table = doc.add_table(rows=1, cols=len(titles))

add_table 方法定义为 add_table(rows, cols, style=None)。它接受三个参数,分别是行数、列数以及样式,其中行数与列数是必填项。如果没有指定 style,那么表格样式会使用当前文档的默认表格样式。

**(2)**设置表格样式

 table.style = 'Light List Accent 1'

style 属性,可读可写表格样式。如果将其设置为 None,那么将移除之前所指定的样式,并使用当前文档的默认表格样式。

注意: 样式名称如果存在 -,会被移除掉。比如 Light Shading - Accent 1 会被转换为 Light Shading Accent 1

‘Light List Accent 1’ 所对应的就是 word 中的 ‘浅色列表 - 着色 1’,其它样式命名规则与此相同:

**(3)**设置表格标题

title_cells = table.rows[0].cells
    for i in range(len(titles)):
        title_cells[i].text = titles[i]
  • 这里的 titles 是标题列表,形如 [xx,xx]。
  • Table 对象的 rows 实例包含多个 _Row 对象。每个 _Row 对象都包含一个 cells 列表,即包含多个 _Cell 实例。_Cell 实例中的 text 属性即可设置单元格的文本内容。

**(4)**设置表格内容

    for d in data:
        row_cells = table.add_row().cells
        for i in range(len(titles)):
            row_cells[i].text = d[i]

Table 对象中有一个 add_row() 方法,它会返回一个 _Row 实例。这个实例最后会被添加到表格末尾。


在 word 中创建表格总结如下:

  1. 创建 Table 对象。
  2. 设置表格样式。
  3. 设置标题。
  4. 设置内容。
发布了601 篇原创文章 · 获赞 668 · 访问量 88万+

猜你喜欢

转载自blog.csdn.net/deniro_li/article/details/103585529