方法一:写入新建文档 安装第三方库 pip install python-docx 实现代码 # pip install python-docx from docx import Document from docx.shared import Pt # 简单的打开word,输入数据,关闭word document = Document() # 向word里增加段落 document.add_paragraph('hello') document.save('./doc/test.docx') # 在一个段落中增加文字 document = Document() paragraph = document.add_paragraph('Hello, ') # 增加文字 paragraph.add_run('tgenkidu') # 设置word字体大小 style = document.styles['Normal'] font = style.font font.size = Pt(10) document.save('./doc/test.docx') 运行结果 注意 运行python时,要写入的word文档应处于关闭状态。
方法二:运用模板写入word文档 本例创建了 模板.docx生成模板2.docx,也可使用已有模板进行修改,加以应用。
安装第三方库 pip3 install docxtpl -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com 因直接安装报错,所以选择了国内的库