使用Requests下載圖片並使用openpyxl將圖片寫入Excel中


之前爬取的數據,是直接把圖片url放在Excel中的,或者直接下載到一個目錄中,或者轉存到自家服務器上,拿到新的鏈接。
這邊收到需求要求把圖片縮小到140*140直接放到Excel單元格中,操作如下。

使用Requests下載圖片

使用Requests下載單張圖片,只要將相應對象的二進制內容,二進制格式保存即可,示例如下:

import requests
url = 'https://www.bulgari.cn/media/catalog/product/cache/17a97ae74dcd05e3600304dfd5afbc49/3/5/356325_001.png'
res = requests.get(url)
file_name = url.split('/')[-1]
with open(file_name, 'wb') as f:
    f.write(res.content)

如果圖片較大,為了優化性能,可以分塊寫入:

...
with open(file_name, 'wb') as f:
    for data in res.iter_content(128):
            f.write(data)

使用openpyxl,在Excel中插入圖片

使用openpyxl,可以使用sheet對象的add_image('圖片文件路徑或Image對象', '錨點')來在一個單元格中插入對象,使用openpyxl中的Image對象還可以設置圖片尺寸。示例如下。

from openpyxl import Workbook
from openpyxl.drawing.image import Image
wb = Workbook()
sh = wb.active
img = Image('demo.png')
img.width, img.height=140, 140
sh.add_image(img, 'A1')
wb.save('demo.xlsx')

保存后,打開Excel,效果如下。

另外可以通過sh.column_dimensions['A'].width=140來設置列寬,通過 sh.row_dimensions[1].height=140來設置行高。

完整代碼

import requests
from openpyxl import Workbook
from openpyxl.drawing.image import Image

IMG_COL = 'A'

def save_img(url):
    res = requests.get(url)
    file_name = url.split('/')[-1]
    with open(file_name, 'wb') as f:
         for data in res.iter_content(128):
            f.write(data)
    return file_name

def insert_img(sh, line, file_name):
    sh.row_dimensions[line].height=140
    img = Image(file_name)
    img.width, img.height=140, 140
    sh.add_image(img, 'A1')

if __name__ == "__main__":
    wb = Workbook()
    sh = wb.active
    sh.column_dimensions[IMG_COL].width=140
    url = 'https://www.bulgari.cn/media/catalog/product/cache/17a97ae74dcd05e3600304dfd5afbc49/3/5/356325_001.png'
    file_name = save_img(url)
    insert_img(sh, 1, file_name)
    wb.save('demo.xlsx')

多張圖片,添加循環即可。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM