本文共 1384 字,大约阅读时间需要 4 分钟。
我们可以使用 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]
**(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 中创建表格总结如下:
转载地址:http://nrbcf.baihongyu.com/