Python-docx操作word-操作table表格

新增表格

创建一个2行2列的表格 Table,如下:

table = document.add_table(rows=2, cols=2)

获取单元格 方式一

获取第一行第二列的单元格类,如下:

cell = table.cell(m, n)

解释:

  • m:行索引,从0开始

  • n:列索引,从0开始

写入数据

如下:

cell.text = '这是第一行第二列的单元格'

例子

from docx import Document
document = Document()

table = document.add_table(rows=2, cols=2)
cell = table.cell(0, 1)
cell.text = '第一行第二列的单元格'

document.save('filename.docx')

获取行

row = table.rows[m]

解释:

  • m:行索引,从0开始

获取单元格 方式二

通过行获取单元格

row.cells[m]

解释

  • m:当前行的单元格索引,从0开始

例子

from docx import Document
document = Document()

table = document.add_table(rows=2, cols=2)

row = table.rows[1]
row.cells[0].text = '第二行第一列'
row.cells[1].text = '第二行第二列'

document.save('filename2.docx')

增加行

row = table.add_row()

例子

from docx import Document
document = Document()

table = document.add_table(rows=2, cols=2)
cell = table.cell(0, 1)
cell.text = '第一行第二列'

row = table.add_row()

row.cells[0].text = '第三行第一列'
row.cells[1].text = '第三行第二列'

document.save('filename3.docx')

获取表格内容

将所有表格的单元格内容打印出来,如下:

from docx import Document
doc=Document('testdoc.docx')
ts=doc.tables
for t in ts:
    rows=t.rows
    for row in rows:
        cols=row.cells
        for col in cols:
            print(col.text,end='   ')
        print()

原文出处:/show_1IX1RlnCqpH6.html