我使用 JsonConverter VBA 模块将 Excel 中的数据导出为标准 JSON 格式。JSON 输出类似于以下内容:-
[{
"Manufacturer": "Ford",
"Code": 5551234,
"Model": "Escort"
"Status": "Available"
},
{
"Manufacturer": "Ford",
"Code": 5551335,
"Model": "Mondeo"
"Status": "Out of stock"
},
{
"Manufacturer": "Ford",
"Code": 5551240,
"Model": "Fiesta"
"Status": "Available"
},
{
"Manufacturer": "BMW",
"Code": 5552567,
"Model": "M1"
"Status": "Available"
},
{
"Manufacturer": "BMW",
"Code": 5552328,
"Model": "M2"
"Status": "Available"
},
{
"Manufacturer": "BMW",
"Code": 5552573,
"Model": "M3"
"Status": "Out of stock"
}
]
我使用的 VBA 代码如下:-
Sub Excel2JSON()
Dim excelRange As Range
Dim jsonItems As New Collection
Dim jsonDictionary As New Dictionary
Dim jsonFileObject As New FileSystemObject
Dim jsonFileExport As TextStream
Dim i As Long
Dim cell As Variant
Set excelRange = Cells(1, 1).CurrentRegion
For i = 2 To excelRange.Rows.Count
jsonDictionary("Manufacturer") = Cells(i, 1)
jsonDictionary("Code") = Cells(i, 2)
jsonDictionary("Model") = Cells(i, 3)
jsonDictionary("Status") = Cells(i, 4)
jsonItems.Add jsonDictionary
Set jsonDictionary = Nothing
Next i
Set jsonFileExport = jsonFileObject.CreateTextFile(".../cardata.json", True)
jsonFileExport.WriteLine (JsonConverter.ConvertToJson(jsonItems, Whitespace:=3))
End Sub
然后,我使用以下脚本将该 JSON 导入 HTML 表:-
$(document).ready(function() {
$.ajax({
url: "cardata.json",
method: "GET",
dataType: "json",
success: function(data) {
var $tbody = $("table#data tbody");
$.each(data, function(i, data) {
var $tr = $("<tr></tr>");
$tr.appendTo($tbody);
var $td = $("<td></td>");
$td.html(data.Manufacturer)
.appendTo($tr);
$td = $("<td></td>");
$td.html(data.Code)
.appendTo($tr);
$td = $("<td></td>");
$td.html(data.Model)
.appendTo($tr);
$td = $("<td></td>");
$td.html(data.Status)
.appendTo($tr);
});
},
});
});
问题/问题是双重的。我想将 JSON 导入 2 个不同的 HTML 表而不是一个(一个表用于福特,另一个用于宝马等)。我知道下面的 JSON 将与 2 个不同的表一起使用,但是我无法修改 VBA 代码来创建如下所示的 JSON:-
{
"Ford": [{
"Code": 5551234,
"Model": "Escort"
"Status": "Available"
},
{
"Code": 5551335,
"Model": "Mondeo",
"Status": "Out of stock"
},
{
"Code": 5551240,
"Model": "Fiesta",
"Status": "Available"
}
],
"BMW": [{
"Code": 5552567,
"Model": "M1",
"Status": "Available"
},
{
"Code": 5552328,
"Model": "M2",
"Status": "Available"
},
{
"Code": 5552573,
"Model": "M3",
"Status": "Out of stock"
}
]
}
另一种方法是保持 JSON 相同,但更改脚本将其导入 2 个不同 HTML 表的方式。