Excel表格中的數據可以導出為多種格式,包括JSON格式。以下是使用VBA代碼在Excel表格中導出JSON數據的示例:
Sub ExportToJson() Dim rowNum As Integer Dim colNum As Integer Dim field As String Dim value As String Dim jsonStr As String Dim rowJsonStr As String rowNum = ActiveSheet.UsedRange.Rows.Count colNum = ActiveSheet.UsedRange.Columns.Count jsonStr = "[" For i = 2 To rowNum rowJsonStr = "{" For j = 1 To colNum field = ActiveSheet.Cells(1, j).Value value = ActiveSheet.Cells(i, j).Value rowJsonStr = rowJsonStr & """" & field & """:""" & value & """" If j<>colNum Then rowJsonStr = rowJsonStr & "," Next j rowJsonStr = rowJsonStr & "}" jsonStr = jsonStr & rowJsonStr If i<>rowNum Then jsonStr = jsonStr & "," Next i jsonStr = jsonStr & "]" Open "D:\test.json" For Output As #1 Print #1, jsonStr Close #1 End Sub
這段VBA代碼將表格中的數據按照JSON格式導出到D盤上的test.json文件中。其中,首先使用ActiveSheet.UsedRange.Rows.Count和ActiveSheet.UsedRange.Columns.Count獲取行和列的數量,然后遍歷表格中的每一行和每一列,將數據按照JSON格式拼接成字符串,最后輸出到文件中。