运用Python将图片写入到word中

Talk is cheap,show me the code!

(我英语好我来翻译一哈o( ̄︶ ̄)o:不bb上代码!)

from docx import Document
from docx.shared import Inches
from PIL import Image

string = '文字内容'
images = '0.jpg'  # 保存在本地的图片
doc = Document()
doc.add_paragraph(string)  # 添加文字

try:
    doc.add_picture(images, width=Inches(6))  # 添加图, 设置宽度
except Exception:
    jpg_ima = Image.open(images)  # 打开图片
    jpg_ima.save('0.jpg')  # 保存新的图片
    doc.add_picture(images, width=Inches(2))  # 添加图, 设置宽度

doc.save('word文档一.docx')  # 保存路径

其中可能会遇到这样的报错:

Could not find a version that satisfies the requirement PIL (from versions: ) No matching distribution found for PIL

遇到报错此处参考另一篇博文帮你解决:
解决没有PIL包的报错

这里参考一下这位老哥的文档:
https://blog.csdn.net/qq_24591139/article/details/109767104python将图片批量写入word文档中

def picture_docx(path_picture,path_docx):
    # 要插入的图片所在的文件夹
    #fold = 'C:\\Users\\Administrator\\Desktop\\tu'
    fold = path_picture

    # os.walk(fold)没有返回值,所以这么做显然没有结果,是错的
    # pics=list(os.walk(fold)[3])
    # # pics.pop()
    # print(pics)

    # pics是图片的名字
    # root是string类型, dirs和pics是list类型
    for root, dirs, pics in os.walk(fold):
        doc = Document()
        for i in range(0, len(pics)):

            # 不需要把文件后缀名去掉,后面的PIL库里的open可以直接识别出文件名后缀
            # print(pics[i],'\n')
            # pics[i] = os.path.splitext(pics[i])[0]
            # print(pics[i], '\n')

            # 我前半部分的路径直接复制黏贴了,没用root和dirs
            filepath = path_picture + pics[i]
            # filepath = root + '\\' + str(pics[i])

            try:
                doc.add_picture(filepath, width=Inches(6), height=Inches(3))
            except Exception:
                pic_tmp = Image.open(filepath)
                # 如果格式有问题,就用save转换成默认的jpg格式
                pic_tmp.save(pic_tmp)
                # 把处理后的图片放进Document变量doc中
                doc.add_picture(filepath, width=Inches(6), height=Inches(3))

            # 把Document变量doc保存到指定路径的docx文件中
            doc.save(path_docx + "PLS.docx")

            # 输出保存成功的标志
            print("pic", i + 1, "successfully added.")

  • 1
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hi洛一

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值