JSON导入到Excel

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

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

由于这是VBA,我将使用COM调用xmlhttprequest,但是以同步方式使用它,不会破坏VBA的单线程执行环境,以这种方式说明post和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   

所以现在可以调用上面的命令返回服务器的响应:

Dim request As New syncWebRequest
request.ajaxGet "http://localhost/ClientDB/AllClients?format=json" 
Dim json as string 
json = request.Response

这里的问题是我们希望能够以某种方式读取从服务器返回的数据,而不是直接操作JSON字符串。对我有用的是使用VBA-JSON(谷歌代码导出here)COM类型集合处理JSON数组和字典来处理成员及其声明,使用解析器工厂方法基本上使创建这些字典集合更简单。

所以现在我们可以解析JSON:

[{"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

这很好,但是像什么能编辑和回传数据呢?嗯,还有一个方法toString从上面的[Collection / Dictionary] JSON数据创建一个JSON字符串,假设服务器接受JSON回来。

http://stackoverflow.com/questions/8044423/json-import-to-excel

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:JSON导入到Excel