使用前提:
- 第一行不能是合併單元格,openpyxl處理會出現問題
- openpyxl version > 3.0
- 如果圖片地址不是以.jpg結尾,需要更改requests部分代碼
from openpyxl import load_workbook
from openpyxl.drawing.image import Image
import requests
wb =load_workbook("example.xlsx")
ws = wb["sheet1"]
file_path = "E:\Jupyter\向Excel中插入圖片\img\{}.jpg"
location = [] # 存放座標列表
for row in ws.rows:
for cell in row:
if cell.value and str(cell.value).startswith("http://"):
location.append(cell.coordinate) # 返回座標
pic= requests.get(cell.value)
cell.value = "" # 刪除原有鏈接數據
with open(file_path.format(cell.coordinate),"wb") as f:
f.write(pic.content)
for coordinate in location:
file_path = "E:\Jupyter\向Excel中插入圖片\img\{}.jpg".format(coordinate)
img = Image(file_path)
newsize =(112.5,150) # 設置圖片大小
img.width, img.height = newsize
column = "".join(re.findall(r'[A-Za-z]', coordinate)) # 列的位置
row = int(re.sub("\D", "", coordinate) ) # 行的位置
ws.column_dimensions[column].width = 13.5 # 設置列寬
ws.row_dimensions[row].height = 114 # 設置行高
ws.add_image(img, coordinate)
wb.save("result.xlsx")