吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 2005|回复: 33
收起左侧

[Python 原创] python批量插入图片到word文档里并且实现分栏排版

[复制链接]
Eks6666 发表于 2024-12-27 13:29
本帖最后由 Eks6666 于 2024-12-27 15:01 编辑

[Python] 纯文本查看 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from docx import Document
from docx.shared import Inches
import os
 
 
img_folder=input('请输入图片目录路径:')
img_paths = (os.path.join(img_folder, f) for f in os.listdir(img_folder) if f.endswith(('.jpg','.png')))
 
# 创建一个新的word文档
doc = Document()
 
width = Inches(2.8)
height = Inches(1.7)
 
# 将所有图片插入到word文档中
table = doc.add_table(rows=0, cols=2)
for i, img_path in enumerate(img_paths):
        if i % 2 == 0:
                row_cells = table.add_row().cells
        cell = row_cells[i % 2]
        para = cell.add_paragraph()
        run = para.add_run()
        pic = run.add_picture(img_path, width=width, height=height)
        print(f'{os.path.basename(img_path)}已插入到word文档中...')
        para.alignment = 1
 
print('所有图片已全部插入...')
 
doc.save('图片.docx')

效果图:
ps.jpg

免费评分

参与人数 13吾爱币 +17 热心值 +11 收起 理由
顶蘑菇 + 1 + 1 我很赞同!
MuLinShang + 1 + 1 我很赞同!
苏紫方璇 + 5 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!
leta + 1 + 1 这个很实用啊,感谢分享!
aaddmmiinn + 1 + 1 谢谢@Thanks!
ysy2001 + 1 + 1 谢谢@Thanks!
levap + 1 谢谢@Thanks!
晓风残月祭 + 1 + 1 我很赞同!
jaffa + 1 + 1 谢谢@Thanks!
52bojie + 1 + 1 谢谢@Thanks!
Jupiter888 + 1 热心回复!
hfol85 + 1 + 1 谢谢@Thanks!
tangyangkun + 1 + 1 谢谢@Thanks!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

hfol85 发表于 2024-12-27 17:23
cai2532 发表于 2024-12-27 17:11
真的很不错,如果能在图片下面再增加图片对应名称效果会更好。楼主教下怎么才能实现这个效果?

基于楼主的创意由AI辅助修改的。希望有用。感谢楼主。
[Python] 纯文本查看 复制代码
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
import tkinter as tk
from tkinter import filedialog
from docx import Document
from docx.shared import Inches
import os
 
def get_folder_path():
    folder_selected = filedialog.askdirectory()
    folder_path.set(folder_selected)
 
def get_output_file_path():
    output_file_selected = filedialog.asksaveasfilename(
        defaultextension=".docx",
        filetypes=[("Word文档", "*.docx"), ("所有文件", "*.*")],
        title="选择输出文件的位置和名称"
    )
    output_filename.set(output_file_selected)
 
def create_document():
    img_folder = folder_path.get()
    output_file = output_filename.get()
     
    if not img_folder:
        status_label.config(text='请先选择图片文件夹。')
        return
 
    if not output_file:
        status_label.config(text='请先选择输出文件的位置和名称。')
        return
 
    image_paths = [os.path.join(img_folder, f) for f in os.listdir(img_folder) if f.lower().endswith(('.jpg', '.jpeg', '.png'))]
     
    if not image_paths:
        status_label.config(text='在指定的文件夹中没有找到支持的图片格式。')
        return
 
    status_label.config(text='正在创建文档...')
    window.update()
     
    doc = Document()
    width = Inches(2.8)
    height = Inches(1.7)
    table = doc.add_table(rows=0, cols=2)
 
    for i, img_path in enumerate(image_paths):
        if i % 2 == 0:
            row_cells = table.add_row().cells
        cell = row_cells[i % 2]
        para = cell.add_paragraph()
        run = para.add_run()
        try:
            pic = run.add_picture(img_path, width=width, height=height)
            para.alignment = 1
            # 在图片下方添加文件名
            file_name_para = cell.add_paragraph(os.path.basename(img_path))
            file_name_para.alignment = 1
            status_label.config(text=f'{os.path.basename(img_path)} 已插入到 word 文档中...')
            window.update()
        except Exception as e:
            status_label.config(text=f'无法插入 {os.path.basename(img_path)},原因:{e}')
            window.update()
     
    if image_paths and (i + 1) % 2!= 0:
        status_label.config(text='最后一行只有一个图片,如有需要请手动调整格式。')
     
    try:
        doc.save(output_file)
        status_label.config(text=f'所有图片已全部插入,文档保存为 "{os.path.basename(output_file)}"。')
        window.update()
        open_document(output_file)
    except Exception as e:
        status_label.config(text=f'无法保存文档,原因:{e}')
 
def open_document(file_path):
    try:
        if os.path.isfile(file_path):
            if os.name == 'nt'# Windows系统
                os.startfile(file_path)
            elif os.name == 'posix'# macOS或Linux系统
                os.system(f'open "{file_path}"')
            else:
                status_label.config(text='不支持的操作系统,无法自动打开文档。')
    except Exception as e:
        status_label.config(text=f'无法打开文档,原因:{e}')
 
window = tk.Tk()
window.title('图片插入Word文档工具')
 
folder_path = tk.StringVar()
output_filename = tk.StringVar()
 
tk.Label(window, text='图片文件夹路径:').grid(row=0, column=0)
entry_folder_path = tk.Entry(window, textvariable=folder_path, width=40).grid(row=0, column=1)
browse_button_folder = tk.Button(window, text='浏览', command=get_folder_path).grid(row=0, column=2)
 
tk.Label(window, text='输出文件路径:').grid(row=1, column=0)
entry_output_filename = tk.Entry(window, textvariable=output_filename, width=40).grid(row=1, column=1)
browse_button_output = tk.Button(window, text='浏览', command=get_output_file_path).grid(row=1, column=2)
 
start_button = tk.Button(window, text='开始', command=create_document).grid(row=2, column=1)
 
status_label = tk.Label(window, text='', fg='blue')
status_label.grid(row=3, column=1)
 
window.mainloop()
hfol85 发表于 2024-12-27 17:14
本帖最后由 hfol85 于 2024-12-27 17:21 编辑

用AI辅助改了一版带操作界面的。
image.png
aahong 发表于 2024-12-27 13:46
shengforever 发表于 2024-12-27 14:40
收藏了,排版这块很nice
wkdxz 发表于 2024-12-27 14:48
很不错的代码,感谢提供分享
智勇1900 发表于 2024-12-27 14:58
同理可以试试其他功能,也是插入图片
 楼主| Eks6666 发表于 2024-12-27 15:00
shengforever 发表于 2024-12-27 14:40
收藏了,排版这块很nice

感谢铁子的大力支持
china-ray 发表于 2024-12-27 15:52
这个代码挺好,之前都是手动一张一张排版的。就是不知道针对不同尺寸、横版、竖版的图片也是同样的压缩尺寸吗?
390660860 发表于 2024-12-27 16:43
谢谢!留存备用
cai2532 发表于 2024-12-27 17:11
真的很不错,如果能在图片下面再增加图片对应名称效果会更好。楼主教下怎么才能实现这个效果?
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2025-5-18 06:39

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表