将网络图片从URL加载到Excel工作表
Contents
[
Hide
]
从URL加载图像到Excel工作表
Aspose.Cells for Python via .NET API 提供了简单便捷的方法,将图片从网址加载到Excel工作表中。本文介绍了下载图片数据到流中,再用 Aspose.Cells for Python via .NET API 插入到工作表中的方法。使用此方法,图片成为Excel文件的一部分,且每次打开工作表时不会重新下载。
示例代码
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
from PIL import Image | |
import io | |
from aspose.cells import Workbook, CellsHelper | |
# For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
# Define memory stream object | |
obj_image = io.BytesIO() | |
# Define a string which will hold the web image url | |
s_url = "https://docs.aspose.com/cells/images/Aspose-image-for-open-graph.jpg" | |
try: | |
# Instantiate the web client object | |
response = requests.get(s_url) | |
# Now, extract data into memory stream downloading the image data into the array of bytes | |
obj_image.write(response.content) | |
# Create a new workbook | |
wb = Workbook() | |
# Get the first worksheet in the book | |
sheet = wb.worksheets[0] | |
# Get the first worksheet pictures collection | |
picts = sheet.pictures | |
# Insert the picture from the stream to B2 cell | |
picts.add(1, 1, obj_image) | |
# Save the excel file | |
wb.save("webimagebook.out.xlsx") | |
except Exception as ex: | |
# Write the error message on the console | |
print(ex) |
可能有需要始终使用最新的图片,直接从URL加载。实现方式请参考 Insert a Linked Picture from Web Address。通过此方法,每次打开工作表时,图片都从URL加载。