# 增加表格
table = doc1.add_table(rows=1, cols=3)
# 设置表格的边框样式
table.style = 'Table Grid'
# 设置表格字段
cells = table.rows[0].cells
cells[0].text = '编号'
cells[1].text = '姓名'
cells[2].text = '职业'
# 表格数据
data = (
(1, '吕小布', '将军'),
(2, '诸葛亮', '军事'),
(3, '刘备', '主攻'),
)
# 添加数据
for i, n, w in data:
tmp_cell = table.add_row().cells
tmp_cell[0].text = str(i)
tmp_cell[1].text = n
tmp_cell[2].text = w
读取文档
python复制代码
from docx import Document
# 打开文档
doc1 = Document('./文档.docx')
# 读取数据-段落
for p in doc1.paragraphs:
print(p.text)
# 读取表格
for t in doc1.tables:
for row in t.rows:
for c in row.cells:
print(c.text, end=' ')
print()