【无标题】

单元格中插入图片

要在表格中插入图片,你可以使用add_picture方法插入图片,并指定插入到哪个单元格中。这里有个例子:

python 复制代码
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属性来访问表格中的列,并设置每个列的宽度。这里有个例子:

python 复制代码
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 column widths
table.columns[0].width = Inches(2.0)
table.columns[1].width = Inches(3.0)
table.columns[2].width = Inches(4.0)

# Add cell content
row = table.rows[0]
row.cells[0].text = 'Column 1'
row.cells[1].text = 'Column 2'
row.cells[2].text = 'Column 3'

document.save('my_table.docx')

在这个例子中,我们首先创建一个2行3列的表格,并将autofit参数设置为False。接着,我们设置每个列的宽度,分别为2、3和4英寸。最后,我们在第一行的每个单元格中添加文本。

注意,在使用Table.columns属性时,索引从0开始。因此,我们使用table.columns0来访问第一列,使用table.columns1来访问第二列,以此类推。

python生成的word表格设置内容居中

python生成的word表格设置内容内容默认左对齐,生成的表格不美观可以使用一下代码将内容居中

需要导入的库

python 复制代码
from docx.enum.table import WD_TABLE_ALIGNMENT

将单元格内容设置居中

python 复制代码
for r in range(6):#循环将每一行,每一列都设置为居中
    for c in range(8):
        table.cell(r, c).paragraphs[0].paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER
相关推荐
莪_幻尘2 分钟前
4 个 3D 游戏,总体积 3.82MB:拆解 Claude 的 one-shot 工程链路
前端·ai编程·three.js
Highcharts.js10 分钟前
Highcharts智能数据分析平台Orbit 多语言配置技术文档
java·前端·javascript·highcharts·orbit·智能数据分析·设置文档
草莓熊Lotso21 分钟前
【C++ 基于微服务的即时通讯系统】文件存储子服务实战:UUID生成、文件IO封装与全接口单元测试
开发语言·网络·数据库·c++·微服务·架构·单元测试
ABAP-張旺1 小时前
SAP ABAP 实战:SAP GUI上做 HTML 看板报表
前端·html·sap·abap
时间的情敌1 小时前
Cesium 建筑单体化、3DTiles 分类、楼层显隐、分户高亮(BIM + 倾斜孪生高频)
前端·3d·cesium
IT_陈寒1 小时前
JavaScript项目实战经验分享:从内存泄漏到性能优化的血泪史
前端·人工智能·后端
进击的荆棘1 小时前
MySQL——库的操作
数据库·mysql
2601_967980112 小时前
“小程序·云开发”上线 助力开发者的高效利器
数据库·存储管理·小程序云开发·云函数·开发者工具
zhangjw342 小时前
1-9 SELECT 查询基础:where、group by、having、order by、limit offset
数据库·postgresql·pg数据库
唐老板2 小时前
Postgres 慢查询,先取证再动手
数据库·ai编程