我有一个javascript对象,其中包含其他对象:
{
"10": {},
"12": {
"20": {
"value": 1,
"id": 1,
},
"100": {
"value": 12,
"id": 1,
}
},
"14": {
"100": {
"value": 14,
"id": 2,
}
},
"16": {},
"18": {},
"20": {
"100": {
"value": 23,
"id": 1,
},
"150": {
"value": 56,
"id": 3,
}
},
"22": {},
"24": {},
"26": {
"50": {
...
我想将其导出为xlsx文件,但我遇到了一些问题。
我主要使用js-xlsx对其文档并不是很有帮助,alasql。
为更简单的数据结构创建这样的文件非常简单。但是当我尝试使用自己的结构创建它时,我遇到了一些问题。
首先尝试这样做:
alasql('SELECT * INTO XLSX("test.xlsx",{headers:true}) FROM ?',[$scope.TestData]);
无法打印[Object]
而不是实际值。
尝试自己创建单元格,最后得到一个空文件。
function sheet_from_array_of_arrays(data, opts) {
var ws = {};
var range = {s: {c:10000000, r:10000000}, e: {c:0, r:0 }};
var row1 = 0;
for (var R in data) {
if (data.hasOwnProperty(R)) {
var row2 = 0;
for (var C in data[R]) {
if (data[R].hasOwnProperty(C)) {
var col = 0;
for (var K in data[R][C]) {
if (data[R][C].hasOwnProperty(C)) {
var RR = row1 + row2;
var CC = col;
if(range.s.r > RR) range.s.r = RR;
if(range.s.c > CC) range.s.c = C;
if(range.e.r < RR) range.e.r = RR;
if(range.e.c < CC) range.e.c = CC;
var cell = {v: data[R][C][K] };
if(cell.v == null) continue;
var cell_ref = XLSX.utils.encode_cell({c:CC,r:RR});
if(typeof cell.v === 'number') cell.t = 'n';
else if(typeof cell.v === 'boolean') cell.t = 'b';
else if(cell.v instanceof Date) {
cell.t = 'n'; cell.z = XLSX.SSF._table[14];
cell.v = datenum(cell.v);
}
else cell.t = 's';
ws[cell_ref] = cell;
col = col + 1;
}
}
row2 = row2 + 1;
}
}
row1 = row1 + 1;
}
}
if(range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);
return ws;
}
function Workbook() {
if(!(this instanceof Workbook)) return new Workbook();
this.SheetNames = [];
this.Sheets = {};
}
var wb = new Workbook(), ws = sheet_from_array_of_arrays($scope.TestData);
/* add worksheet to workbook */
wb.SheetNames.push(ws_name);
wb.Sheets[ws_name] = ws;
var wbout = XLSX.write(wb, {bookType:'xlsx', bookSST:true, type: 'binary'});
function s2ab(s) {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), "test.xlsx")
有没有办法让我用上面提到的对象创建一个xlsx文件?
答案 0 :(得分:0)
您可以使用SEARCH运算符来解析嵌套的JSON对象:
var data = {
"10": {},
"12": {
"20": {
"value": 1,
"id": 1,
},
"100": {
"value": 12,
"id": 1,
}
},
"14": {
"100": {
"value": 14,
"id": 2,
}
},
"16": {},
"18": {},
"20": {
"100": {
"value": 23,
"id": 1,
},
"150": {
"value": 56,
"id": 3,
}
}
};
var res = alasql('SEARCH OF(@a) OF(@c) \
RETURN(@a AS a,@c AS c, _->[value] AS [value], _->id AS id) \
INTO XLSX("test406.xlsx",{headers:true}) \
FROM ?',[data]);
下面: