当前位置:   article > 正文

基于python的word批量图文排版_python word排版

python word排版

1、缘起

在最近的工作中,需要将大量的图片按一定顺序在word里排版,并要求每页内容为:序号 + 图像文件名 + 图片。之前用VBA也实现了要求,但奈何对VBA不熟悉,不利于之后的扩展,因此看看万能的python能不能实现。

2、尝试

黄天不负有心人,终于找到了python操作word的神器----python-docx
官方文档: https://pythondocx.readthedocs.io/en/latest/
看过官方文档后,就开始了简单尝试。
1、创建文档:

from docx import Document
from docx.shared import Inches
from docx.oxml.ns import qn

document = Document()          # 创建一个文档对象
  • 1
  • 2
  • 3
  • 4
  • 5

2、插入段落:

paragraph = document.add_paragraph("我实例化了一个文档")  #插入一个段落
style = p.style
font = p.style.font
font.name = '华文新魏'
font._element.rPr.rFonts.set(qn('w:eastAsia'), '华文新魏')  # 设置字体
font.size = Pt(20)  # 设置字号
document.save("./第一个文档.docx")  # 保存文档
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

3、插入图片:

document.add_picture(image_path, width=Inches(5), height=Inches(4)) #插入图片
  • 1

看看效果:
在这里插入图片描述
4、实现需求:

from docx import Document
from docx.shared import Inches
import os
import pandas as pd
from docx.shared import Pt
from docx.oxml.ns import qn

document = Document()          # 实例化文档
path = 'C:/Users/Administrator/Desktop/'
file_name = '县外就读'
type_file = path + file_name + "/"
id_name = path+"名单.xlsx"

isd = pd.read_excel(id_name)
for id in isd.values:
    # print(id)
    name = str(id[0])+id[1]
    images = type_file + name +".png"
    p = document.add_paragraph(name)
    style = p.style
    font = p.style.font
    font.name = '华文新魏'
    font._element.rPr.rFonts.set(qn('w:eastAsia'), '华文新魏')
    font.size = Pt(20)
    try:
        document.add_picture(images, width=Inches(9), height=Inches(2))  # 插入图片
    except:
        pass

    document.add_page_break()  # 插入分页符
    print(images)


document.save(path+"{}.docx".format(file_name))   # 保存文件
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

看看效果:
在这里插入图片描述
大功告成,每页一张图片,都是序号+文件名+图片的形式,总共711张。

结语

三点感受,1、python是真的强;2、python是真的强;3、python是真的强!
当然python-docx还有很多其他功能,今后需要的时候在继续探索吧!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/711012
推荐阅读
相关标签
  

闽ICP备14008679号