在 json_to_sheet 之后使用 XLSX js 对列进行排序和过滤

Sort and filter columns with XLSX js after json_to_sheet

我正在使用这个 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|

我的问题是所有未列出的属性都只是附加在末尾。

我不t/can不更改我的 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 |

你有更好的解决方案吗?请分享 :)