Python-docx

Python-docx 安装使用说明

Python-docx模块下载

进入 https://pypi.org/project/python-docx/ ,使用pip安装或是下载压缩包进行安装
1、pip install python-docx
在这里插入图片描述
2、下载压缩包
在这里插入图片描述

Python-docx模块使用

导入Document类
from docx import Document

新建一个空白Word文档
document = Document()
https://python-docx.readthedocs.io/en/latest/api/document.html#id1

设置文档页边距
#导入inches
from docx.shared import Inches

https://python-docx.readthedocs.io/en/latest/api/section.html#sections-objects
#设置上下左右页边距
sections = document.sections
section = sections[0]
section.top_margin = Inches(0.7)
section.bottom_margin = Inches(0.7)
section.left_margin = Inches(0.7)
section.right_margin = Inches(0.7)

红色箭头为页边距Inches(0.7),可根据实际设置值
在这里插入图片描述
设置标题
使用Document提供的add_heading方法
h = document.add_heading(“标题标题标题”)

添加段落
使用Document提供的add_paragraph方法
p = document.add_paragraph(“段落段落段落”)

段落属性设置
#导入WD_ALIGN_PARAGRAPH,Pt
from docx.shared import Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH

更多属性参考 https://python-docx.readthedocs.io/en/latest/api/text.html#paragraphformat-objects

#段落格式(段落的对齐设置为居中。此段落与后续段落之间出现的间距的值设为0)
p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
p.paragraph_format.space_after = Pt(0)

#段落字体大小设置
p.style.font.size = Pt(18)

添加表格
https://python-docx.readthedocs.io/en/latest/api/table.html#id1
使用Document提供的add_table方法
#添加一个4行4列表格
table = document.add_table(rows=4,cols=4,style=“Table Grid”)
在这里插入图片描述
#合并单元格(cell(x,y)中 x代表行,y代表列,都从0开始,比如第一行第一列即为cell(0,0))
table.cell(0,0).merge(table.cell(0,1))
table.cell(1,2).merge(table.cell(1,3))
table.cell(2,0).merge(table.cell(3,0))
table.cell(2,2).merge(table.cell(3,2))
在这里插入图片描述
设置单元格底纹(好像还没有开放相应接口)
参考 https://groups.google.com/forum/#!topic/python-docx/-c3OrRHA3q
#导入
from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml
#设置单元格cell(0,0)底纹
shading = parse_xml(r’<w:shd {} w:fill=“E5DFEC”/>’.format(nsdecls(‘w’)))
table.cell(0,0)._tc.get_or_add_tcPr().append(shading)
设置多个单元格不能用同一个shading,更换一下变量名,否则只有最后一个应用shading的生效
在这里插入图片描述
保存
使用Document提供的save方法
#可填实际存放路径,只填文件名,则保存在调用程序当前文件夹中
document.save(‘test.docx’)


  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值