今天分享一个将图片批量插入word文档的小脚本,本脚本可以实现 jpg\png图片,可以混合在一起!
首先 我们需要设置每页word文档的排版需求,如:每页6张图片,一共是3行2列
pics_per_page = 6,这是每页几张图片
pics_per_row = 2,这是每行几张图片
视频展示,看一下是否是你想要的效果:
奉上全部的代码:
pic_folder = “./图片存放”,这里是你的图片存放的文件夹地址
import os
from PIL import Image
from docx import Document
from docx. shared import Inches
def f2 ( ) :
pics_per_page = 6
pics_per_row = 2
doc = Document( )
pic_folder = "./图片存放"
pic_files = os. listdir( pic_folder)
pic_files = [ f for f in pic_files if f. endswith( '.jpg' ) or f. endswith( '.png' ) ]
for i, pic_file in enumerate ( pic_files) :
if i % pics_per_row == 0 :
p = doc. add_paragraph( )
img_path = os. path. join( pic_folder, pic_file)
img = Image. open ( img_path)
width, height = img. size
aspect_ratio = height / float ( width)
new_width = 2.7
new_height = aspect_ratio * new_width
p. add_run( ) . add_picture( img_path, width= Inches( new_width) , height= Inches( new_height) )
doc. save( 'pics.docx' )
f2( )
进阶版-将图片的名字放在图片的下面
def f2 ( ) :
pics_per_page = 6
pics_per_row = 2
doc = Document( )
pic_folder = "./修改尺寸后"
pic_files = os. listdir( pic_folder)
pic_files = [ f for f in pic_files if f. endswith( '.jpg' ) or f. endswith( '.png' ) ]
count = 0
f_n_list = [ ]
for i, pic_file in enumerate ( pic_files) :
if i % pics_per_row == 0 :
p = doc. add_paragraph( )
img_path = os. path. join( pic_folder, pic_file)
img = Image. open ( img_path)
width, height = img. size
aspect_ratio = height / float ( width)
new_width = 2.5
new_height = aspect_ratio * new_width
p. add_run( ) . add_picture( img_path, width= Inches( new_width) , height= Inches( new_height) )
count+= 1
f_n_list. append( os. path. basename( pic_file) )
if count % 2 == 0 :
doc. add_paragraph( ) . add_run( ' ' . join( f_n_list) ) . font. size = Pt( 9 )
count = 0
print ( f_n_list)
f_n_list. clear( )
doc. save( 'pics.docx' )
f2( )
此外该专栏还写有多篇关于python操作word的文章,欢迎大家关注、订阅
观看
希望对大家有帮助,如有错误,欢迎指正
致力于办公自动化的小小程序员一枚
希望能得到大家的【一个免费关注】!感谢!