python批量插入图片到表格
时间: 2025-06-29 08:12:11 浏览: 21
### 使用Python批量插入多张图片到Excel
为了实现将多个图像文件批量插入到Excel工作表中,可以采用`openpyxl`库来操作Excel文档,并利用循环结构处理多个图片文件。下面展示了具体的操作方式。
#### 准备阶段
确保环境中已安装必要的Python包,可以通过pip工具完成安装:
```bash
pip install openpyxl pillow
```
这里不仅依赖于`openpyxl`用于读写.xlsx文件格式,还需要`Pillow`支持图片加载与调整[^2]。
#### 实现过程
创建一个新的Excel文件并向其中插入一系列图片的过程如下所示:
```python
from openpyxl import Workbook
from openpyxl.drawing.image import Image
import os
def insert_images_to_excel(image_folder, output_file='output.xlsx'):
wb = Workbook()
ws = wb.active
row_num = 1
col_num = 1
max_per_row = 4 # 每行最多放置四张图片
for idx, img_name in enumerate(os.listdir(image_folder), start=1):
if not (img_name.lower().endswith('.png') or img_name.lower().endswith('.jpg')):
continue
cell_ref = f'{chr(65 + ((idx-1)%max_per_row))}{row_num}'
image_path = os.path.join(image_folder, img_name)
img = Image(image_path)
# 设置图片尺寸保持原比例缩小至适合单元格显示
scale_factor = min(ws.column_dimensions[cell_ref].width/float(img.width),
ws.row_dimensions[row_num].height/float(img.height))
new_width = int(img.width * scale_factor)
new_height = int(img.height * scale_factor)
img.width = new_width
img.height = new_height
ws.add_image(img, cell_ref)
if idx % max_per_row == 0:
row_num += 1
wb.save(output_file)
insert_images_to_excel('path/to/image/folder')
```
上述代码定义了一个函数`insert_images_to_excel()`接收两个参数:一个是存储待插入图片的文件夹路径;另一个是输出的目标Excel文件名称,默认为'output.xlsx'^[2]^。
此段程序会遍历指定目录下的所有图片文件(.png,.jpg),依次将其按照一定规律排列在新的Excel工作簿的不同单元格位置上,并适当调整每张图片大小以便更好地适应表格布局。
阅读全文
相关推荐

















