JSON导入到Excel

时间:2011-11-08 00:07:00

标签: json excel api google-docs

是否可以在宏中编写JSON调用脚本?

我想通过API连接获取JSON字符串。看起来问题是Excel期望参数在HTML字符串中传递,但JSON传递HTML主体中的参数。有什么想法吗?

2 个答案:

答案 0 :(得分:42)

由于这是VBA,我使用COM来调用xmlhttprequest,但是以同步的方式使用它,以免扰乱VBA的单线程执行环境,一个示例类,用于说明post和{{ 1}}以这种方式请求如下:

get

现在你可以调用上面的内容来返回服务器的响应:

'BEGIN CLASS syncWebRequest

Private Const REQUEST_COMPLETE = 4

Private m_xmlhttp As Object
Private m_response As String

Private Sub Class_Initialize()
    Set m_xmlhttp = CreateObject("Microsoft.XMLHTTP")
End Sub

Private Sub Class_Terminate()
    Set m_xmlhttp = Nothing
End Sub


Property Get Response() As String
    Response = m_response
End Property

Property Get Status() As Long
    Status = m_xmlhttp.Status
End Property

Public Sub AjaxPost(Url As String, Optional postData As String = "")
    m_xmlhttp.Open "POST", Url, False
    m_xmlhttp.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
    m_xmlhttp.setRequestHeader "Content-length", Len(postData)
    m_xmlhttp.setRequestHeader "Connection", "close"
    m_xmlhttp.send (postData)
    If m_xmlhttp.readyState = REQUEST_COMPLETE Then
        m_response = m_xmlhttp.responseText
    End If
End Sub

Public Sub AjaxGet(Url As String)
    m_xmlhttp.Open "GET", Url, False
    m_xmlhttp.setRequestHeader "Connection", "close"
    m_xmlhttp.send
    If m_xmlhttp.readyState = REQUEST_COMPLETE Then
        m_response = m_xmlhttp.responseText
    End If
End Sub

'END CLASS syncWebRequest   

这里的问题是我们希望能够以某种方式读取从服务器返回的数据,而不是直接操作JSON字符串。对我有用的是使用VBA-JSON(谷歌代码导出here)COM类型Dim request As New syncWebRequest request.ajaxGet "http://localhost/ClientDB/AllClients?format=json" Dim json as string json = request.Response 来处理JSON数组,使用Collection来处理成员及其声明,使用解析器工厂方法Dictionary基本上使创建这些词典集合变得更加简单。

现在我们可以解析JSON:

Parse

如下所示:

[{"Name":"test name","Surname":"test surname","Address":{"Street":"test street","Suburb":"test suburb","City":"test city"}}]

这很好,但是能够编辑和回发数据等内容呢?那么还有一个方法Set clients = parser.parse(request.Response) For Each client In clients name = client("Name") surname = client("Surname") street = client("Address")("Street") suburb = client("Address")("Suburb") city = client("Address")("City") Next 来从上面的[Collection / Dictionary] JSON数据创建一个JSON字符串,假设服务器接受了JSON。

答案 1 :(得分:9)

我为此写了一个.NET Excel-Addin。它是一个通用的Excel JSON客户端,可以通过http直接将任何JSON对象流式传输到Excel。

可在此处找到文档和安装说明: http://excel-requests.pathio.com/en/master/

这里是GitHub链接: https://github.com/ZoomerAnalytics/excel-requests