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’)