Excel是大家經常使用的電子表格軟件,它可以方便地管理數據。但在實際應用中,我們可能需要將Excel中的數據導出為JSON格式,以便于Web應用的使用。這時候,我們可以使用Excel轉換為JSON的工具。
Sub ExportJSON() Dim wb As Workbook Dim ws As Worksheet Dim LastRow As Long Dim LastCol As Long Dim i As Long, j As Long Dim dict As New Scripting.Dictionary Dim row As Range Dim arr() As Variant Dim json As String '獲取當前工作表 Set wb = ActiveWorkbook Set ws = wb.ActiveSheet '獲取最后一行和最后一列 LastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row LastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column '讀取每一行數據 For i = 2 To LastRow Set row = ws.Rows(i) arr = row.Value '將每一行數據轉換為字典 For j = 1 To LastCol If Not dict.Exists(arr(1, j)) Then dict.Add arr(1, j), arr(i, j) Else dict(arr(1, j)) = dict(arr(1, j)) & "," & arr(i, j) End If Next j Next i '生成JSON json = "{" For Each key In dict.Keys json = json & """" & key & """:" json = json & "[" & dict(key) & "]," Next key json = Left(json, Len(json) - 1) json = json & "}" '輸出JSON Debug.Print json End Sub
從上面的代碼可以看出:
- 先獲取當前工作表、最后一行和最后一列
- 然后讀取每一行數據,并將每一行數據轉換為字典
- 最后生成JSON字符串
通過Excel轉換為JSON的工具,我們可以方便地將Excel中的數據導出為JSON格式,以便于Web應用的使用。