Load a Web Image from a URL into an Excel Worksheet
Load an Image from a URL into an Excel Worksheet
Aspose.Cells for Python via .NET API provides a simple and easy way to load images from URLs into Excel Worksheets. This article explains downloading the image data into a stream and then inserting it into the worksheet using the Aspose.Cells for Python via .NET API. Using this method, the images becomes a part of the excel file and are not downloaded every time the worksheet is opened.
Sample Code
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) |