将图片写入到excel某一列
参考视频:https://www.bilibili.com/video/BV1L5411e7Zj?p=1&share_medium=iphone&share_plat=ios&share_session_id=F43BCE3C-CD23-4CF8-B998-C2FE8BD1F0F6&share_source=WEIXIN&share_tag=s_i×tamp=1644493555&unique_k=eYCgqEs
方法:https://openpyxl.readthedocs.io/en/latest/usage.html#inserting-an-image
为了使得图片和内容一一对应,先将内容插入到excel中,然后再将图片插入到内容的旁边列
具体代码:
from openpyxl import load_workbook
from openpyxl.drawing.image import Image
def insert_img(
filename,
by_col,
to_col,
img_folder
):
'''
插入图片到 excel
:param filename: 文件路径
:param by_col: 依靠的列(A,B,C...)
:param to_col: 插入到列(A,B,C...)
:param img_folder: 图片源的文件夹,绝对路径
:return: None
'''
wb = load_workbook(filename) # 读取传入的文件路径名
ws = wb.active
for i,c in enumerate(ws[by_col],start=1): # i 用于取出excel索引列数字,start=1指定从1开始(excel索引列从1开始,但是openpyxl默认是从0开始)
# enumerate枚举函数
name = c.value.split(" ")[-1]
# print(name)
img_ffn = os.path.join(img_folder,name + ".jpg")
imgsize = (200, 125)
img = Image(img_ffn)
print(img.path)
img.width, img.height = imgsize
print(i,img_ffn)
try: # 如果找不到会崩掉,所以增加异常处理
ws.add_image(
img,
anchor=to_col + str(i) #锚点,B列+索引,将i的int类型转换成str
)
except:
print(c.value,'匹配不到图片')
wb.save(filename)
if __name__ == '__main__':
insert_img(
'111.xlsx', # 如果excel表格和py文件在同一文件夹,可以直接只写文件名,如不在同一文件夹,则需要写excel的绝对路径
'A',
'B',
img_folder='D:\python\code\Test\TestScrapy\Imgtest'
)
print("over!")