Python写入word文档

目录

1.写入简单段落、插入图片

2.设置字体

设置全文字体:

设置段落字体: 

3.插入表格并填充内容、设置对齐方式

4.设置页面布局

1.写入简单段落、插入图片

import docx
from docx import shared
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT

doc=docx.Document() #创建内存中的word文档对象
doc.add_paragraph("这是第一段") #写入若干段落
doc.add_paragraph("这是第二段")
doc.add_picture('img.png',width=shared.Cm(10))    #插入图片,设置宽度为10cm
doc.paragraphs[-1].alignment=WD_PARAGRAPH_ALIGNMENT.CENTER    #设置最后一段居中对齐,这里可以使图片居中
doc.save("E:\desktop\test.docx") #保存才能看到结果

在保存时如果遇到下面类似的错误:

OSError: [Errno 22] Invalid argument: 'E:\\desktop\try.docx'

尝试更改文件名,因为文件名与反斜线可能组成了转义字符。也可以在路径名前加入r来取消转义字符的作用:

file.save(r"E:\desktop\try.docx") 

2.设置字体

设置全文字体:

import docx
from docx.shared import Pt
from docx.oxml.ns import qn

doc=docx.Document()
doc.styles['Normal'].font.name = 'Times New Roman'
doc.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
doc.add_paragraph('这是中文,this is English')
doc.save('d:/Desktop/test4.docx')

设置段落字体: 

import docx
from docx.shared import Pt
from docx.oxml.ns import qn

doc=docx.Document()

p1 = doc.add_paragraph()
text1 = p1.add_run("第一段文字是中文;The first paragraph is in Chinese")
text1.font.size = Pt(15)                                # 设置字体大小
text1.bold = True                                      # 设置字体是否加粗
text1.font.name = 'Times New Roman'                     # 设置西文字体
text1.element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')  # 设置中文字体

p2 = doc.add_paragraph()
text2 = p2.add_run("第二段文字是英文;The second paragraph is in English")
text2.font.size = Pt(10)
text2.bold = False
text2.font.name = 'Times New Roman'
text2.element.rPr.rFonts.set(qn('w:eastAsia'), '黑体')

doc.save('d:/desktop/test3.docx')

3.插入表格并填充内容、设置对齐方式

import docx
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_ALIGN_VERTICAL
from docx import shared
from docx.shared import Cm,Inches,Pt

doc=docx.Document()
table=doc.add_table(rowNums,colNums) #括号内为插入表格的行列数
#可用len(table.rows)、len(table.columns)获取表格的行列数
table.cell(0,0).text='1' #在第一行第一列的单元格填充字符1,表格的行列都从0开始计数

#设置单元格对齐方式为水平居中|左对齐|右对齐|两端对齐
table.cell(0,0).paragraphs[0].paragraph_format.alignment=WD_ALIGN_PARAGRAPH.CENTER|WD_ALIGN_PARAGRAPH.LEFT|WD_ALIGN_PARAGRAPH.RIGHT|WD_ALIGN_PARAGRAPH.DISTRIBUTE
 #设置单元格对齐方式为垂直居中|顶部对齐|底部对齐
table.cell(0,0).vertical_alignment=WD_ALIGN_VERTICAL.CENTER|WD_ALIGN_VERTICAL.TOP|WD_ALIGN_VERTICAL.BOTTOM
#以下为在单元格(0,1)中插入图片,并设置宽度为5cm(当只设置图片一个方向的尺寸(宽或高)时,另一方向会自动缩放)
table.cell(0,1).paragraphs[-1].add_run().add_picture(r“imgPath\img.tif",width=shared.Cm(5))
#在单元格(0,2)中插入图片,并设置高度为5 Inches:
table.cell(0,2).paragraphs[-1].add_run().add_picture(r“imgPath\img2.tif",height=shared.Inches(5))

'''此句也可用多条语句替换:
    p=table.cell(0,1).paragraphs[-1]
    run=p.add_run()
    run.add_picture(r“imgPath\img.tif",width=docx.shared.Cm(5))
'''
#在表格最后插入一行(最下方)和一列(最右侧),插入列时需要指定宽度(这里为5cm)
table.add_row()
table.add_column(Cm(5))

#行列的索引
row=table.rows[1]
column=table.columns[1]
#设置行高列宽
table.rows[1].height=Cm(1)
table.cell(1,2).width=Cm(3)    #同列单元格宽度相同,不同时以最大宽度为准
#行的删除:可通过row._element.getparent().remove()函数实现
row._element.getparent().remove(row._element) 
#列的删除:列没有像行那样的remove()函数,可通过遍历列中的单元格进行删除.但表格中的cell按行存储,删除第i行的某个单元格后,每行的cell数并不变化,逻辑上第i+1行的第一个单元格会补到第i行的最后一个单元格,所以与外观不同。
for cell in column.cells: 
    cell._element.getparent().remove(cell._element) 


doc.save("filename.docx")

4.设置页面布局

页面方向有横向与竖向,新建Document时,默认的是竖向页面,要设置为我们目标的横向,需要设置三个参数,分别为section.orientation, section.page_width, section.page_height。

注:如果只设置参数section.orientation=WD_ORIENT.LANDSCAPE,不设置另外两个参数,页面方向并不发生变化;如果设置了section.page_height,section.page_width两个参数,不设置section.orientation,页面会根据前两个参数设置页面尺寸进行调整。

import docx
from docx.shared import Cm,Inches,Pt
from docx.enum.section import WD_ORIENT
doc=docx.Document()
sec=doc.sections #获取文档章节列表,新建的文档只有一节
sec0=sec[0] #将第一节命名为sec0
#新建文档默认为竖向,改为横向须设置三个参数:
sec0.orientation=WD_ORIENT.LANDSCAPE #设置页面方向为横向须同时设置高度和宽度才有用
sec0.page_height=Cm(21)
sec0.page_width=Cm(29.7)
#若只设置第一个而不设置另外两个,则页面方向不发生变化;如果只设置后两个,则页面的宽和高会改变,但仍为纵向

sec0.left_margin=shared.Cm(1) #设置页边距均为1cm
sec0.right_margin=shared.Cm(1)
sec0.top_margin=shared.Cm(1)
sec0.bottom_margin=shared.Cm(1)

doc.save("filename.docx")

练习:以下程序的功能是将一个文件夹中的图片以表格形式排列在word中:

import docx
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_ALIGN_VERTICAL
from docx.enum.section import WD_ORIENT
from docx import shared
from docx.shared import Cm,Inches,Pt
import os
doc=docx.Document()
sec=doc.sections
sec0=sec[0]
sec0.orientation=WD_ORIENT.LANDSCAPE
sec0.page_height=Cm(21)
sec0.page_width=Cm(29.7)
sec0.left_margin=shared.Cm(1) #设置页边距均为1cm
sec0.right_margin=shared.Cm(1)
sec0.top_margin=shared.Cm(1)
sec0.bottom_margin=shared.Cm(1)

imgPath=r"imgPath\\"
imgList=[""]+ os.listdir(imgPath)
rowNums=eval(input("请输入包含图片标题在内的行数:"))
colNums=eval(input("请输入列数:"))
table=doc.add_table(rowNums,colNums)
#设置单元格对齐方式为水平居中
table.cell(0,0).paragraphs[0].paragraph_format.alignment=WD_ALIGN_PARAGRAPH.CENTER
 #设置单元格对齐方式为垂直居中
table.cell(0,0).vertical_alignment=WD_ALIGN_VERTICAL.CENTER
for rowNum in range(1,rowNums+1,2):
    for colNum in range(1,colNums+1):
             if (rowNum-1)*colNums/2+colNum>len(imgList)-1:
                 break
             else:
                 try:
                     imgName=imgList[int((rowNum-1)*colNums/2)+colNum]
                     total_imgPath=imgPath+imgName
                     table.cell(rowNum-1,colNum-1).paragraphs[-1].add_run().add_picture(total_imgPath,width=shared.Cm(27/colNums))
                     table.cell(rowNum,colNum-1).text=imgName
                 except: #如果有其它类型的文件则忽略
                    pass
    if (rowNum-1)*colNums/2+colNum>len(imgList)-1:
        break
doc.save(r"e:\desktop\Picture.docx")


ref:https://blog.csdn.net/woshisangsang/article/details/75304228

        python 取消转义字符作用

        Python-docx 读写 Word 文档:插入图片、表格,设置表格样式,章节,页眉页脚等

        利用python自动写Word文档(二)——用python-docx修改页面方向及字体 - 简书

        利用python自动写Word文档(三)——用Python-docx修改表格 - 简书

        python-docx添加和删除表格行、列 - 天涯海角路 - 博客园

        https://zhuanlan.zhihu.com/p/88151371

        python-docx设置图片大小和对齐方式 | 码农家园

    Python-docx 整体修改或者部分修改文字的大小和字体类型_Leeoo_lyq的博客-CSDN博客_python 修改docx        ​

  • 23
    点赞
  • 156
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值