Python-docx库中的table对象是用来创建和操作Word文档中的表格的。以下是一些常用的table对象的用法:
- 创建一个表格
可以使用add_table方法创建一个新的表格,指定表格的行数和列数。例如,以下代码可以创建一个包含3行和4列的空表格:
from docx import Document
from docx.shared import Inches
document = Document()
table = document.add_table(rows=3, cols=4)
- 往表格中添加内容
可以使用add_row方法在表格中添加新的行,并使用add_cell方法在行中添加新的单元格。例如,以下代码可以在表格中添加一些文本:
from docx import Document
from docx.shared import Inches
document = Document()
table = document.add_table(rows=3, cols=4)
# 添加表头
heading_cells = table.rows[0].cells
heading_cells[0].text = 'Name'
heading_cells[1].text = 'Age'
heading_cells[2].text = 'Gender'
heading_cells[3].text = 'Occupation'
# 添加数据行
data = [
('Alice', 25, 'Female', 'Engineer'),
('Bob', 30, 'Male', 'Manager'),
('Charlie', 35, 'Male', 'Doctor')
]
for row in data:
cells = table.add_row().cells
cells[0].text = row[0]
cells[1].text = str(row[1])
cells[2].text = row[2]
cells[3].text = row[3]
- 修改表格样式
可以使用table.style属性来修改表格的样式。例如,以下代码可以将表格的样式设置为"LightShading-Accent1":
from docx import Document
from docx.shared import Inches
document = Document()
table = document.add_table(rows=3, cols=4)
table.style = 'LightShading-Accent1'
这只是Python-docx库中table对象的一些基本用法,如果你需要更多的功能,可以查看Python-docx库的官方文档。