用到XLSX npm包: https://www.npmjs.com/package/xlsx
现在有一组库存数据,按照status做了分组,然后我要把这个分组结果导入excel,结果如下图,也就是导入的过程中要包括导入表头,导入数据体,导入分组头,合并单元格。XLSX包没有提供导入这种数据的工具, 有提供的工具查看XLSX.utils下,比如导入工具
aoa_to_sheet converts an array of arrays of JS data to a worksheet.
json_to_sheet converts an array of JS objects to a worksheet.
table_to_sheet converts a DOM TABLE element to a worksheet.
sheet_add_aoa adds an array of arrays of JS data to an existing worksheet.
sheet_add_json adds an array of JS objects to an existing worksheet.
虽然下面的源数据是json格式,如果不需要导入group那是可以很简单的用json_to_sheet来导入。但是还要穿插group头就不能这样做。
研究了下XLSX的worksheet,她的结构是这样的,有个“!ref” 属性表示数据内容的始终表格坐标,有个“!merges”数组,它用于指定要合并单元格的始终表格坐标。
既然没有现成的工具,那就用数组拼接:
先拼凑excel 内容主题,然后在拼凑merge的数据:
let invGroup = {
"available": [
{
"itemSpecId": "ITEM-1",
"lpId": "ILP-1",
"status": "available",
"qty": 10,
"unit": "EA"
},
{
"itemSpecId": "ITEM-1",
"lpId": "ILP-4",
"status": "available",
"qty": 9,
"unit": "CS"
}
],
"shipped": [
{
"itemSpecId": "ITEM-2",
"lpId": "ILP-2",
"status": "shipped",
"qty": 10,
"unit": "EA"
}
],
"locked": [
{
"itemSpecId": "ITEM-3",
"lpId": "ILP-3",
"status": "locked",
"qty": 10,
"unit": "EA"
}
]
}
function groupDataConvertToAoa(groupData) {
let ws_data =[];
let values = _.values(groupData);
let value = values[0][0];
let header = Object.keys(value);
ws_data.push(header); // 表头数据
_.each(groupData, (values, key)=>{
ws_data.push([[key]]); //group 头数据
_.each(values, value=>{
ws_data.push(Object.values(value)); //主要数据体
});
});
let ws = XLSX.utils.aoa_to_sheet(ws_data); //将数据体塞入sheet
//下面用于计算merge的单元格坐标,拼凑merge表格坐标数据
let maxLength = _.size(header);
let r=1;
let merges=[];
_.each(groupData, (values, key)=>{
merges.push({s: {r: r, c: 0}, e: {r: r, c: maxLength-1}});
r+=_.size(values)+1;
});
ws["!merges"] = merges;
return ws;
}
function writeXLSX(ws) {
let destFile = "./writeExcelOutPut.xlsx";
var workbook = {
SheetNames: [],
Sheets: {}
};
var ws_name = "Test";
workbook.SheetNames.push(ws_name);
/* Load the worksheet object */
workbook.Sheets[ws_name] = ws;
XLSX.writeFile(workbook, destFile);
console.log("done")
}
writeXLSX(groupDataConvertToAoa(invGroup));
结果