在网上浏览了这么久,发现Python-docx离不开table,因为插入图片,图片的居中,都必须用到表格的操作
单元格中插入图片
要在表格中插入图片,你可以使用add_picture方法插入图片,并指定插入到哪个单元格中。这里有个例子:
from docx import Document
from docx.shared import Inches
document = Document()
table = document.add_table(rows=2, cols=2)
# Add image to cell (0, 1)
cell = table.cell(0, 1)
img_path = 'picture.png'
paragraph = cell.paragraphs[0]
run = paragraph.add_run()
run.add_picture(img_path, width=Inches(2.0))
document.save('my_table.docx')
固定列宽
要固定表格的列宽,你可以使用Table.auto_fit方法,并将autofit参数设置为False。然后,可以使用Table.columns属性来访问表格中的列,并设置每个列的宽度。这里有个例子:
from docx import Document
from docx.shared import Inches
document = Document()
table = document.add_table(rows=2, cols=3, style='Table Grid')
# Turn off autofit 固定列宽
table.autofit = False
# Set col

本文介绍了如何使用Python-docx库在Word文档中操作表格,包括插入图片到单元格、固定列宽以及实现内容居中。通过实例展示了如何创建表格、设置图片位置、控制列宽和调整文本对齐方式。
最低0.47元/天 解锁文章
848

被折叠的 条评论
为什么被折叠?



