我正在使用这个 xlsx js库,用于从 Angular5 应用程序中的 TypeScript 对象列表生成 Excel 文件。
我不需要 TypeScript 对象的所有属性,我想以特定方式对其他属性进行排序。
一个简单的 TypeScript 对象列表作为示例:
[
{
"id":"one",
"location":"New York",
"metadata":"just other infos",
"name":"John",
},
{
"id":"two",
"location":"Boston",
"metadata":"just other infos",
"name":"Mark",
},
{
"id":"three",
"location":"Portland",
"metadata":"just other infos",
"name":"Samy",
}
]
想要的 Excel 输出:
|id |name |location |
|one |John |New York |
|two |Mark |Boston |
|three |Samy |Portland |
到目前为止我所拥有的(排序还可以):
const workbook = XLSX.utils.book_new();
const myHeader = ["id","name","location"];
const worksheet = XLSX.utils.json_to_sheet(this.myListOfObjects(), {header: myHeader});
XLSX.utils.book_append_sheet(workbook, worksheet, 'tab1');
XLSX.writeFile(workbook, 'excel_export.xlsb');
但这会生成以下 excel 文件:
|id |name |location |metadata |
|one |John |New York |just other infos|
|two |Mark |Boston |just other infos|
|three |Samy |Portland |just other infos|
我的问题是所有未列出的属性都只是附加在最后。
我不能/不能更改我的 TypeScript 对象。我不想将工作表转换回数组。
最佳答案
我花了一段时间才找到这个简单的解决方案。还有其他可能性,但这是最简单的一种。
可以使用 worksheet['!ref']
缩小 Excel 文件的范围。
所以我将范围从“A1:D4”缩小到“A1:B3”。为此,我获取了 myHeader 列表的长度(该列表应该来自配置文件)。
const range = XLSX.utils.decode_range(worksheet['!ref']);
range.e['c'] = myHeader.length - 1;
worksheet['!ref'] = XLSX.utils.encode_range(range);
完整的代码片段:
const workbook = XLSX.utils.book_new();
const myHeader = ["id","name","location"];
const worksheet = XLSX.utils.json_to_sheet(this.myListOfObjects(), {header: myHeader});
const range = XLSX.utils.decode_range(worksheet['!ref']);
range.e['c'] = myHeader.length - 1;
worksheet['!ref'] = XLSX.utils.encode_range(range);
XLSX.utils.book_append_sheet(workbook, worksheet, 'tab1');
XLSX.writeFile(workbook, 'excel_export.xlsb');
瞧,这将生成以下 excel 文件:
|id |name |location |
|one |John |New York |
|two |Mark |Boston |
|three |Samy |Portland |
你有更好的解决方案吗?请分享 :)
关于javascript - 在 json_to_sheet 之后使用 XLSX js 对列进行排序和过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56854160/