【问题标题】:Open Excel (XLS) file from URL with GET parameters使用 GET 参数从 URL 打开 Excel (XLS) 文件
【发布时间】:2014-11-26 02:17:46
【问题描述】:

我正在尝试使用 GET 参数从 HTTP 链接打开 XLS 文件。如果您只是将链接复制并粘贴到您的网络浏览器中,您将看到它有效。如果我省略 GET 参数,我可以使用 workbooks.open 打开工作簿,但它会打开错误的工作簿,因为您需要 GET 参数来准确提取我想要的内容。

Dim myURL As String
Dim winHttpReq As Object
Set winHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
myURL = "http://www.otcmarkets.com/common/ViewStockScreener.xls?otcMarketTier=&otcMarketTierDesc=&otcMarketTierGroup=&otcMarketTierId=&otcMarketTierGroupDesc=&allTierGroups=true&securityType=CORP&securityTypeDesc=Corporate%20Bond&countryId=&locale=&countryDesc=&localeDesc=&allLocales=true&sicIndustryIdentifier="
winHttpReq.Open "GET", myURL, False
winHttpReq.Send
MsgBox Len(winHttpReq.responseBody)
result = winHttpReq.responseBody

Dim x As Workbooks
Set x = result
x(1).Open

感谢您的帮助!

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    我认为您无法直接从 Excel 中的 URL 打开文件,除非它是 SharePoint 网站。

    我认为您使用 WinHttpRequest 走在正确的轨道上,但您需要在打开文件之前将结果保存到本地磁盘上的文件中。

    Dim myURL As String
    Dim winHttpReq As Object
    Dim responseData() As Byte
    Dim fname As String
    Dim fno As Integer
    
    Set winHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
    
    myURL = "http://www.otcmarkets.com/common/ViewStockScreener.xls?" & _
         "otcMarketTier=&otcMarketTierDesc=&otcMarketTierGroup=&" & _
         "otcMarketTierId=&otcMarketTierGroupDesc=&allTierGroups=true&" & _
         "securityType=CORP&securityTypeDesc=Corporate%20Bond&countryId=&" & _
         "locale=&countryDesc=&localeDesc=&allLocales=true&sicIndustryIdentifier="
    
    winHttpReq.Open "GET", myURL, False
    winHttpReq.Send
    responseData = winHttpReq.responseBody
    
    fname = CurDur & "\ViewStockScreener.xls"
    fno = FreeFile
    Open fname For Binary As #fno
    Put #fno, 1, responseData
    Close #fno
    
    Workbooks.Open fname
    

    responseData 后面的 () 将其声明为变长字节数组。必须先将 responseBody 复制到原始字节数组中,因为将 responseBody 直接写入二进制文件会损坏数据(可能是某些字符编码问题)。

    如果 ViewstockScreener.xls 名称随机化为 GET 请求的结果

    在将响应数据写入文件时,您可以选择所需的任何文件名。如果保留服务器发回的文件名很重要,那实际上有点困难。您必须查看响应标头的 Content-Disposition 字段并从那里解析出文件名。

    【讨论】:

    • 感谢您的回复,有两个问题,我在“Put #fno, responseData()”这一行遇到语法错误,如果 ViewstockScreener.xls 名称因此而随机化该怎么办GET 请求。
    • 非常感谢!字节被我的舌尖抓住了。请解释为什么在 Byte 之后有一个 () 并请更正 Put 到最后,recnumber 需要在那里,就像'Put #fno,, responseData()' 否则它会给我一个错误。一旦解决了这两件事,我会将其标记为最佳答案。
    猜你喜欢
    • 1970-01-01
    • 2020-10-08
    • 2010-10-02
    • 2018-04-17
    • 1970-01-01
    • 2012-02-17
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    相关资源
    最近更新 更多