将 Web 图像从 URL 加载到 Excel 工作表中
Contents
[
Hide
]
将 URL 中的图像加载到 Excel 工作表中
Aspose.Cells for .NET API 提供了一种将图像从 URL 加载到 Excel 工作表中的简单方法。本文介绍了使用 Aspose.Cells 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
// 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); | |
} |
在某些情况下,您总是希望从 URL 获得更新后的图像。为此,您可以按照从网址插入链接图片文章。通过遵循此方法,每次打开工作表时都会从 URL 加载图像。