1、常规操作import
python设置--项目--python解释器--增加软件包Pillow\xlwings
from PIL import Image
import os
import xlwings as xw
2、存放图片的文件夹地址和excel表的引用
img_path = "C:/Users/Administrator/Desktop/ABC/" # 存放图片的文件夹("\"换成"/")
filename = "C:/Users/Administrator/Desktop/1234567.xlsx" # excel表路径
3、xlwings的代码块和OS的图片列表
说明:
ws.range().column 输出是列对应的数字
ws.api.Columns().Insert() 插入列注意大小写
ws.range().colunm_width 和 ws.range().row_height 是列宽和行高设置
ws.range().expand().value 选中表格引用列的数据
app = xw.App(visible=True, add_book=False)
wb = app.books.open(filename)
ws = wb.sheets[0]
to_col = ws.range('A1').column+1 # 图片列名为数字
ws.api.Columns(to_col).Insert() # 引用列后插入一列
ws.range(1, to_col).column_width = 18 # 设置图片列列宽
ws.range(2, 1).expand('down').row_height = 80 # 设置引用列行高
ws.cells(1, to_col).value = '图片' # 图片列标题命名
img_list = os.listdir(img_path)
by_col = ws.range(2, 1).expand('down').value # 选中应用列的数据
4、循环图片并去掉扩展名
for i in img_list:
img_names = i.split(".")[0]
5、循环表格数据和图片名的匹配
说明:图片地址img_name带扩展名
for j in range(1, len(by_col)+1):
# 引用列和图片名字一样,图片地址加名字(含扩展名)
if by_col[j-1] == img_names:
img_name = os.path.join(img_path, '%s' % i)
6、插入图片,并且和单元格大小相匹配
说明:用Image加载图片,用ws.pictures.add()内部参数,和单元格left\top\width\height对齐
# 插入图片在图片列,设置和单元格匹配
img = Image.open(img_name).convert('RGB')
ws.pictures.add(img_name, left=ws.range(j+1, 2).left,
top=ws.range(j+1, 2).top,
width=ws.range(2, 2).width,
height=ws.range(2, 2).height)
7、保存关闭表格退excel应用
wb.save()
# wb.close()
# app.quit()
8、全部代码展示
from PIL import Image
import os
import xlwings as xw
img_path = "C:/Users/Administrator/Desktop/ABC/" # 存放图片的文件夹("\"换成"/")
filename = "C:/Users/Administrator/Desktop/1234567.xlsx" # excel表路径
app = xw.App(visible=True, add_book=False)
wb = app.books.open(filename)
ws = wb.sheets[0]
# last_row = ws.used_range.last_cell.row
to_col = ws.range('A1').column+1 # 图片列名为数字
ws.api.Columns(to_col).Insert() # 引用列后插入一列
ws.range(1, to_col).column_width = 18 # 设置图片列列宽
ws.range(2, 1).expand('down').row_height = 80 # 设置引用列行高
ws.cells(1, to_col).value = '图片' # 图片列标题命名
img_list = os.listdir(img_path)
by_col = ws.range(2, 1).expand('down').value # 选中应用列的数据
for i in img_list:
img_names = i.split(".")[0]
for j in range(1, len(by_col)+1):
# 引用列和图片名字一样,图片地址加名字(含扩展名)
if by_col[j-1] == img_names:
img_name = os.path.join(img_path, '%s' % i)
# 插入图片在图片列,设置和单元格匹配
img = Image.open(img_name).convert('RGB')
ws.pictures.add(img_name, left=ws.range(j+1, 2).left,
top=ws.range(j+1, 2).top,
width=ws.range(2, 2).width,
height=ws.range(2, 2).height)
wb.save()
# wb.close()
# app.quit()