背景
为了加强与日后老板的感情,主动想为老板写点日用的东西,主要是工作太忙啦!与日后老板沟通挺麻烦,其实需求很简单。
需求
将如图excel,excel格式为第一行标题,同一型号x行,x为对应鞋码数量。需要将这几行中对应的浮动图片拿出来另存为图片,命名格式为厂家_商品型号-鞋码_001(颜色),颜色需要是俄语,映射关系老板提供,几行内容就是几行图片。
代码部分(直接用)
代码思路:先用将所有需要保存的图片的新的名称存储到二维数组中,再遍历所有浮动图片,将图片与新的名称保存到目录下。
形象一点的二维数组:
浮动图片1:鞋码1 鞋码2 鞋码3 …
浮动图片2:鞋码1 鞋码2 鞋码3 …
浮动图片3:鞋码1 鞋码2 鞋码3 …
…
浮动图片n:鞋码1 鞋码2 鞋码3 …
getImages.py
import os
from openpyxl import load_workbook
from PIL import Image
import io
color_dic = {}
# 添加颜色映射关系
color_dic['粉色'] ='розовый'
color_dic['白色'] ='белый'
color_dic['紫色'] ='фиолетовый'
color_dic['灰色'] ='серый'
color_dic['米色'] ='бежевый'
color_dic['黑色'] ='чёрный'
color_dic['蓝色'] ='синий'
color_dic['天蓝色'] ='голубой'
color_dic['棕色'] ='коричневый'
color_dic['卡其'] ='хаки'
color_dic['红色'] ='красный'
color_dic['绿色'] ='зелёный'
#图片名称的二维数组
image_arr =[]
def save_images_from_excel(file_path):
script_dir = os.path.dirname(os.path.abspath(__file__)) # 获取脚本所在目录的绝对路径
workbook = load_workbook(file_path)
sheet = workbook.worksheets[0]
file_name = os.path.splitext(os.path.basename(file_path))[0]
# 创建文件夹路径,相对于脚本所在目录
folder_path = os.path.join(script_dir, file_name)
print(folder_path)
if not os.path.exists(folder_path):
os.makedirs(folder_path)
row = 2
img_name_arr=[]
while True:
# 当前行
col_1_value = sheet.cell(row, 4).value
# 下一行
col_2_value = sheet.cell(row+1, 4).value
# 下一行为空且当前行为空(总结束标志)
if col_2_value is None and col_1_value is None:
image_arr.append(img_name_arr)
break
# 当前行为空(一个图片的结束标志)
if col_1_value is None:
print("col_1_value:None")
row += 1
image_arr.append(img_name_arr)
img_name_arr=[]
continue
else:
print("col_1_value:"+col_1_value)
# col_1_value打印部分可以去掉
# 商家
col_4_value = sheet.cell(row=row, column=4).value
# 货号
col_5_value = sheet.cell(row=row, column=5).value
# 颜色
col_11_value = sheet.cell(row=row, column=11).value
# 尺码
col_20_value = sheet.cell(row=row, column=20).value
img_name = f"{col_4_value}_{col_5_value}-{col_20_value}_001({color_dic.get(col_11_value, 'Not-found')}).png"
img_name_arr.append(img_name)
# 更新行数
row += 1
# 打印所有的文件名
# print(len(image_arr),image_arr)
# print(len(sheet._images))
# 获取所有浮动图片并保存
for idx, image in enumerate(sheet._images):
img_names = image_arr[idx]
image_data = image._data()
for name in img_names:
img_path = os.path.join(folder_path, name)
# 将图片保存到文件夹中
# 使用 PIL 库保存图片
with io.BytesIO(image_data) as image_file:
img = Image.open(image_file)
img.save(img_path)
def main():
# 遍历当前目录下的所有xlsx文件
script_dir = os.path.dirname(os.path.abspath(__file__))
print(script_dir)
for file in os.listdir(script_dir):
if file.endswith(".xlsx") and not file.startswith("~$"):
save_images_from_excel(os.path.join(script_dir, file))
main()
交付后
不到100行的代码没什么逻辑,被日后老板连夸牛比,果然难点在未知。
发现文章内的下载需要vip哈,贴个demo的excel,把excel与代码放一起就行了。