我正在开发Asp.net MVC。我想将Excel数据导入到我的一个网格中。我使用ExpandoObject
(动态)读取Excel文件,然后将其转换为键/值对。我想知道如何提取KeyValue对,并以JSON格式从该键/值对生成标题和数据行。
数据将如下所示:
我想将此KeyValue转换为Header并将其转换为:
[
{"CustomerName" : "Messi", "City":"Buenos Aires", "Country" :"Argentina"},
{"CustomerName" : "Ronaldo", "City":"Lisbon", "Country" :"Portugal"},
{"CustomerName" : "Persie", "City":"Amsterdam", "Country" :"Netherlands"},
{"CustomerName" : "Ronnie", "City":"London", "Country" :"England"}
]
我使用了以下jQuery代码段,但它不起作用:
var arr = [];
$.each(dataReceivedFromServer, function (i, data) {
var d = data.Key;
arr.push({
d: data.Value,
});
});
如果我在上面做,它会显示[{"d":"Messi"},{"d":"Buenos Aires"},{"d":"Argentina"}
等等......
简而言之,我想将数据从Excel文件绑定到KendoUI
网格(所有列都是动态的,因为用户可以选择任何文件)。
有谁知道怎么做?
更新#1:
@webkit - 请参阅下图,作为Console.log的输出
答案 0 :(得分:1)
我强烈建议您在收到数据之前对其进行转换,因为它会更可靠。但是,如果无法做到这一点并且您可以保证数据集上存在某些分组规则,则可以应用以下内容:
var customer = {
//this transform asserts the key value collection will be in a groupable order
transform: function(coll, groupBeginKey){
var result = [];
var currentObject = {};
var size = coll.length;
$.each(coll,function(idx,data){
//check if we are beginning
var defined = (typeof(currentObject[data.Key]) !== 'undefined');
if(!defined &&
data.Key === groupBeginKey){
currentObject = {};
}else if((defined &&
data.Key === groupBeginKey)){
result.push(currentObject);
currentObject = {};
}
//set the property on the object
currentObject[data.Key] = data.Value;
//handle last
if(idx >= size-1){
result.push(currentObject);
}
});
return result;
}
};
对于以下数据集(为简单起见,我简化了它):
var data = []
data.push({ "Key": "CustomerName", "Value": "Paul"});
data.push({ "Key": "City", "Value": "Las Vegas"});
data.push({ "Key": "CustomerName", "Value": "George"});
data.push({ "Key": "Zip", "Value": "1234567"});
data.push({ "Key": "City", "Value": "New York"});
data.push({ "Key": "CustomerName", "Value": "Joe"});
data.push({ "Key": "City", "Value": "Omaha"});
断言客户可以从CustomerName分组到City,您可以按如下方式使用它(它将包括具有邮政编码的客户):
var results = customer.transform(data,"CustomerName");
请在以下jsfiddle中查看它(在调试控制台中查看输出):