Load a Web Image from a URL into an Excel Worksheet
Contents
[
Hide
]
Load an Image from a URL into an Excel Worksheet
Aspose.Cells for .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 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
This file contains 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
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Define memory stream object | |
System.IO.MemoryStream objImage; | |
// Define web client object | |
System.Net.WebClient objwebClient; | |
// Define a string which will hold the web image url | |
string sURL = "http:// Www.aspose.com/Images/aspose-logo.jpg"; | |
try | |
{ | |
// Instantiate the web client object | |
objwebClient = new System.Net.WebClient(); | |
// Now, extract data into memory stream downloading the image data into the array of bytes | |
objImage = new System.IO.MemoryStream(objwebClient.DownloadData(sURL)); | |
// Create a new workbook | |
Aspose.Cells.Workbook wb = new Aspose.Cells.Workbook(); | |
// Get the first worksheet in the book | |
Aspose.Cells.Worksheet sheet = wb.Worksheets[0]; | |
// Get the first worksheet pictures collection | |
Aspose.Cells.Drawing.PictureCollection pictures = sheet.Pictures; | |
// Insert the picture from the stream to B2 cell | |
pictures.Add(1, 1, objImage); | |
// Save the excel file | |
wb.Save(dataDir+ "webimagebook.out.xlsx"); | |
} | |
catch (Exception ex) | |
{ | |
// Write the error message on the console | |
Console.WriteLine(ex.Message); | |
} |
There might be cases where you always want the updated image from a URL. To achieve this, you may follow the instructions given in the Insert a Linked Picture from Web Address article. By following this method, the image is loaded from the URL each time the worksheet is opened.