Excel VBA初学----将excel表数据转换为json,POST上传到服务器API接口
2020-04-15 admin vba 1972
VBA代码如下:
Sub ExcelToJSON() Dim sht As Worksheet Set sht = Worksheets("Sheet1") usedRng = sht.UsedRange rowCnt = UBound(usedRng, 1) colCnt = UBound(usedRng, 2) Dim colArr() ReDim colArr(1 To colCnt) For c = 1 To colCnt Dim rowArr() ReDim rowArr(1 To rowCnt) For r = 1 To rowCnt rowArr(r) = usedRng(r, c) Next colArr(c) = """col" + CStr(c) + """:" + arrToStr(rowArr) Next Dim data$ data = arrToStr2(colArr) data = "{""data"":" + data + "}" Debug.Print (data) End Sub Function arrToStr(ByVal arr) arrStr = Join(arr, """,""") arrToStr = "[""" + arrStr + """]" End Function Function arrToStr2(ByVal arr) arrStr = Join(arr, ",") arrToStr2 = "{" + arrStr + "}" End Function Function uploadData2(ByVal url As String, ByVal data As String) Dim http Set http = CreateObject("Microsoft.XMLHTTP") http.Open "POST", url, False http.setRequestHeader "CONTENT-TYPE", "application/json" http.send data If http.Status = 200 Then MsgBox "上传成功" End If End Function
相反的过程,将服务器API接口传过来的JSON转为excel
Sub bluejson() 'ok Dim aa Set x = CreateObject("ScriptControl"): x.Language = "JScript" aa = "{""myname"":""Michael"",""myaddress"":{""city"":""Beijing"",""street"":"" Chaoyang Road "",""postcode"":100025}}" Set y = x.eval("eval(" & aa & ")") MsgBox y.myname MsgBox y.myaddress MsgBox y.myaddress.city MsgBox y.myaddress.postcode 'Stop End Sub
2020.4.19更新记录:
经测试,使用VBA方式来同步数据,还是很不方便的,一是需要excel运行宏,许多人电脑上是禁用宏的;二是需要对每个excel文件进行改造,加入代码,或者将数据复制到运行宏的excel上点击同步上传按钮。
我们的需求的,扫描某个文件夹下的所有excel表格,如果发现修改了,则进行上传更新。为了避免频繁点保存更新,我们还需要判断:打开excel编辑保存,只要不关闭excel,就一直不上传更新,一直到关闭excel表格,才进行上传同步。
最终我们通过编译桌面exe软件,编写服务器API上传接口的方式,实现了这个需求。测试客户端下载:Excel通用查询系统数据同步客户端.zip
目前实现了自动同步(软件打开后不关闭)和手动上传功能。