在數據處理方面,Excel是很方便的工具,然而在前端開發中,我們常常需要將Excel文件轉換成JSON數據格式來展示在頁面上。這個轉換過程可以通過一些工具來實現,比如在線工具json-csv.com或者使用VBA宏編寫代碼來完成轉換。今天我們將介紹使用VBA宏編寫實現Excel轉換成JSON格式的過程。
Sub ConvertToJSON() Dim arr() As String Dim obj As Object Dim i As Integer, j As Integer, k As Integer Dim col As Integer, row As Integer Dim header As String '獲取當前工作表中的數據范圍 col = ActiveSheet.UsedRange.Columns.Count row = ActiveSheet.UsedRange.Rows.Count '遍歷每一行,把數據保存到一維數組arr中 ReDim arr(row - 2) As String k = 0 For i = 2 To row header = "" For j = 1 To col If j = 1 Then header = Cells(1, j).Value Else header = header & "|" & Cells(1, j).Value End If arr(k) = arr(k) & ",""" & Cells(i, j).Value & """" Next j k = k + 1 Next i '創建字典對象并以header為key,將數據添加到字典中 Set obj = CreateObject("Scripting.Dictionary") For i = 0 To UBound(arr) If Not obj.Exists(Split(header, "|")(0) & "_" & Split(header, "|")(1)) Then obj.Add Split(header, "|")(0) & "_" & Split(header, "|")(1), "[]" End If obj(Split(header, "|")(0) & "_" & Split(header, "|")(1)) = obj(Split(header, "|")(0) & "_" & Split(header, "|")(1)) & IIf(obj(Split(header, "|")(0) & "_" & Split(header, "|")(1)) = "[]", "[", ",") obj(Split(header, "|")(0) & "_" & Split(header, "|")(1)) = obj(Split(header, "|")(0) & "_" & Split(header, "|")(1)) & "{" & Mid(arr(i), 2) & "}" Next i '將字典對象轉換成JSON格式的字符串并輸出 Debug.Print "{" For Each key In obj Debug.Print """" & key & """:" & Replace(obj(key), "[,", "[") & "]," Next key Debug.Print "}" End Sub
上述代碼可將Excel中的數據轉化成嵌套的JSON格式。具體實現過程如下:
首先獲取當前工作表中的數據范圍,然后遍歷每一行,在一維數組arr中存儲數據并以'|'符號將列名拼接起來作為key。再以字典對象的形式存儲數據,以第一個和第二個列名拼接的字符串作為新的key,將數據按著key分組。最后遍歷字典對象,將數據轉換成JSON格式的字符串并輸出。
總的來說,這個轉換的過程雖然比較繁瑣,但是只需要在VBA中編寫一次,在以后的使用中可以大大提高效率。