namespace DemoAddinExcel
{
public static class MyFunctions
{
[ExcelFunction(Category = "GetImageFromURL", Description = "Tải hình ảnh từ website vào Excel")]
public static void GETIMAGE(string url, [ExcelArgument(AllowReference = true)] object arg)
{
ExcelReference theRef = (ExcelReference)arg;
Excel.Application xlapp = (Excel.Application)ExcelDnaUtil.Application;
Workbook wbook = xlapp.ActiveWorkbook;
Worksheet worksheet = wbook.ActiveSheet as Worksheet;
var cell = wbook.ActiveSheet.Cells[theRef.RowFirst + 1, theRef.ColumnFirst + 1];
var imageStreamAysnc = DownloadAsync(url);
string tempFilename = Path.GetTempFileName();
File.WriteAllBytes(tempFilename, (byte[])imageStreamAysnc);
cell.Worksheet.Shapes.AddPicture(tempFilename, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, cell.Left, cell.Top, cell.Width, cell.Height);
File.Delete(tempFilename);
;
}
public static object DownloadAsync(string url)
{
// Don't do anything else here - might run at unexpected times...
return ExcelAsyncUtil.Run("DownloadAsync", url,
delegate { return Download(url); });
}
static byte[] Download(string url)
{
var data = new WebClient().DownloadData(url);
return data;
}
}
}