如何通过C#将图像从URL添加到Excel工作表

这是目标:

1)从URL获取图像,在这种情况下,Google静态地图API

在这里输入图像说明

2)将此图像插入到Excel工作表中。 如果我必须创build(或使用现有的)形状并将背景设置为图像,那我可以。 我也可以插入特定的单元格。 我可以通过Google静态地图API(请参阅上面的URL)定义图片大小,以便始终知道。


我没有完全清楚如何做到这一点,而不是直接将文件保存到文件系统。

我目前有这样的代码获取图像的MemoryStream格式:

public static MemoryStream GetStaticMapMemoryStream(string requestUrl, string strFileLocation) { try { HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK) throw new Exception(String.Format( "Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription)); using (BinaryReader reader = new BinaryReader(response.GetResponseStream())) { Byte[] lnByte = reader.ReadBytes(1 * 700 * 500 * 10); using (FileStream lxFS = new FileStream(strFileLocation, FileMode.Create)) { lxFS.Write(lnByte, 0, lnByte.Length); } MemoryStream msNew = new MemoryStream(); msNew.Write(lnByte, 0, lnByte.Length); return msNew; } } } catch (Exception e) { System.Windows.Forms.MessageBox.Show(e.Message); return null; } } 

请注意,在上述代码的中间,我也将图像写入文件系统。 如果可能,我想避免这部分。

无论如何,我的代码可以创build一个矩形,调用上面的序列来保存图像,然后抓取图像并填充矩形的背景:

 Excel.Shape shapeStaticMap = wsNew2.Shapes.AddShape(Office.MsoAutoShapeType.msoShapeRectangle, 0, 0, 700, 500); string strFileLocation = @"C:\Temp\test.jpg"; MemoryStream newMS = GetStaticMapMemoryStream(strStaticMapUrl, strFileLocation); shapeStaticMap.Fill.UserPicture(strFileLocation); 

所以这里真正的问题是,我想跳过“写入文件,然后从文件中抓取”来回。 这似乎是一个不必要的步骤,我预计它也会弄乱文件权限和什么不是。

UPDATE

好的,所以我基本放弃了,并使用本地文件。 这工作了一段时间,但现在我试图重新工作这个代码从不同的来源,我知道图像大小提前从一个图像。 上面的方法要求我事先知道图像的大小。 如何修改上面的代码dynamic使用任何图像大小?

使用此版本的GetStaticMapMemoryStream:

  public static MemoryStream GetStaticMapMemoryStream(string requestUrl) { try { HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK) throw new Exception(String.Format( "Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription)); var responseStream = response.GetResponseStream(); var memoryStream = new MemoryStream(); responseStream.CopyTo(memoryStream); memoryStream.Position = 0; return memoryStream; } } catch (Exception e) { Console.WriteLine(e.Message); return null; } }