【Python模块】docx操作Word文档

pip install python-docx #安装docx

doc = Document() # 创建空白doc文档
head = doc.add_heading(“”, level=1) #添加标题 level是当前标题的索引
run = head.add_run(“Python操作模块doxc操作Word文档”)
head.alignment = WD_ALIGN_PARAGRAPH.CENTER#居中
run.font.size = Pt(23) #字体大小单位有pt,mm,cm
run.font.color.rgb = RGBColor(1, 1, 1) # 引用颜色库里的颜色 rgb红绿蓝
run.font.name = “宋体” # 设置字体样式

操作单元格

table1 = doc.add_table(rows=4, cols=8) #添加4行5列的表格
table1.autofit = False #设置自动表格自动对齐否
table1.style = “Table Grid” # 设置表格样式为实线

设置表格宽度

table1.rows[0].width = Pt(68) / table1.cell(0, 0).width = Pt(30)

设置表格高度

table1.rows[0].height = Pt(68) / table1.cell(0, 0).height= Pt(30)

合并单元格

table1.cell(0, 0).merge(table1.cell(0, 1))
table1.cell(0, 0).text = ‘123’ #设置单元格第一格的内容为123

添加图片

p = document.add_paragraph()
run = p.add_run()
run.add_picture(‘图片路径’)

保存文件

doc.save(‘Demo.doc’)

发表评论

邮箱地址不会被公开。 必填项已用*标注