将http get请求图像转换为Excel ActiveSheet.Pictures
我有一个从request.responseBody获得的图像,我如何将其传递到excel,而不使用计算机存储器中的临时文件 详情:将http get请求图像转换为Excel ActiveSheet.Pictures,excel,vba,serverxmlhttp,Excel,Vba,Serverxmlhttp,我有一个从request.responseBody获得的图像,我如何将其传递到excel,而不使用计算机存储器中的临时文件 详情: 我在响应体中使用RESTAPI和图像 我不想在我的桌面上有临时文件 挑战是将API的响应转换为Pictures.Insert或Shapes.AddPicture 我用的是这样的东西: Sub GetPicAPI() Dim myUrl As String ' path of image Dim myPicture As Pi
- 我在响应体中使用RESTAPI和图像
- 我不想在我的桌面上有临时文件
- 挑战是将API的响应转换为Pictures.Insert或Shapes.AddPicture
Sub GetPicAPI()
Dim myUrl As String ' path of image
Dim myPicture As Picture ' embedded image
Dim MyImage As String ' create string to receive image in text format
Dim myFile As String
Dim datim As String
Set request = CreateObject("MSXML2.ServerXMLHTTP")
datim = Format(CStr(Now), "yyyy_mm_dd_hh_mm_ss") 'datetime to generate file
myFile = Application.DefaultFilePath & "\phototemp" & datim & ".jpeg"
myUrl = "https://images.contoso.com/api/GetPic?pwd=1234=&id=1234res=low"
request.Open "GET", myUrl, False ' Where to get image
request.send ' Send the request for the webpage.
MyImage = StrConv(request.responseBody, vbUnicode) ' Get the webpage response text into response variable.
Open myFile For Output As #1 'open file to save image
Print #1, MyImage 'write to file
Close #1 'close file
Set myPicture = ActiveSheet.Pictures.Insert(myFile) 'put image into cell
End Sub
您是否尝试过直接传递URL:
ActiveSheet.Pictures.Insert(URL)
?对于图像,您可以使用Shapes.AddPicture
方法,您可以使用URL而不是参数FileName
的本地路径。虽然您可以直接传递URL,但它可能仍会在您的计算机上创建一个临时文件。然而,直接使用URL有一个缺点。如果发生错误,您得到的唯一信息是图片无法插入。但你不会知道为什么。我建议编写一些代码来下载文件,然后插入它。通过这种方式,您可以控制下载并获得有关出错原因的详细信息。与URL端点响应和HTTP通信时间相比,磁盘读/写时间可能很短…@MarkF如果您想问一些问题,请开始一个新问题。请注意,磁盘上不需要管理1000个文件,您可以反复使用相同的文件/文件名。如果在形状中使用LinkToFile:=False
。AddPicture
则图片将被嵌入,而不是链接到文件名。这样,您可以在添加文件后立即删除磁盘上的文件(现在Excel文件中保存了一份副本)。因此,您需要的一切都在Excel文件本身中(例如,如果您将它发送给磁盘上没有图片的其他人,它仍然可以工作)。