programing

Excel로의 JSON Import

elseif 2023. 4. 14. 21:16

Excel로의 JSON Import

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(Google 코드 내보내기) COM 유형을 사용하는 것이 효과적입니다.CollectionJSON 어레이와Dictionary파서 팩토리 방식으로 회원과 그 선언을 처리하다Parse이렇게 하면 사전을 훨씬 쉽게 만들 수 있습니다.

이제 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을 다시 받아들인다고 가정합니다).

라고 썼습니다.이 경우 NET Excel-Addin.이것은 모든 JSON 개체를 http를 통해 Excel로 직접 스트리밍하는 일반적인 Excel JSON 클라이언트입니다.

문서 및 설치 절차는 http://excel-requests.pathio.com/en/master/ 에서 확인할 수 있습니다.

여기 GitHub 링크가 있습니다.https://github.com/ZoomerAnalytics/excel-requests

언급URL : https://stackoverflow.com/questions/8044423/json-import-to-excel