如何在node js中在一个csv文件中制作多个表?

x9ybnkn6  于 2022-12-22  发布在  Node.js
关注(0)|答案(1)|浏览(195)

我想将数据导出为csv文件。我想在一个csv文件中创建多个表,但没有找到在node.js中执行相同操作的方法。有人能帮助解决这个问题吗?

cyvaqqii

cyvaqqii1#

通过使用options中的属性title(作为参数传递给ExportToCsv),可以将多个表导出到单个csv文件。
第1步:让我们获得第一个表的csv等价物,并将其插入csv文件。

var data_one = [ // Table one data to be represented as csv
       {
        "id": 1,
        "name": "Vinayak",
        "age": 33
       },
       {
        "id": 2,
        "name": "Ganesh",
        "age": 28
       },
       {
        "id": 3,
        "name": "Sundar",
        "age": 45
       }
      ];

  const table_one_options = {  // Table one options
  fieldSeparator: ',',
  quoteStrings: '"',
  decimalSeparator: '.',
  showLabels: true,
  showTitle: true,
  title: 'Two table Report',
  filename: 'GenerateCSV',
  useTextFile: false,
  useBom: true,
  useKeysAsHeaders: true};

  const csvExporter_one = new ExportToCsv(table_one_options);
  var table_one_csv = csvExporter_one.generateCsv(data_one, true);  // Here pass 'true' as the second parameter in order to obtain only the csv and not to download the csv file

从上面的代码中,我们已经获得了变量table_one_csv中table_one的csv等效值
第2步:现在这个csv作为ExportToCsv的第二个示例的标题

var data_two =  [  // Table two data to be represented as csv
    {
      name: 'Test 1',
      age: 13,
      average: 8.2,
      approved: true,
      description: "Description A"
    },
    {
      name: 'Test 2',
      age: 11,
      average: 8.2,
      approved: true,
      description: "Description B"
    },
    {
      name: 'Test 4',
      age: 10,
      average: 8.2,
      approved: true,
      description: "Description C"
    },
  ];

  const table_two_options = {  // Table two options
  fieldSeparator: ',',
  quoteStrings: '"',
  decimalSeparator: '.',
  showLabels: true,
  showTitle: true,
  title: table_one_csv,  // table_one_csv obtained in step 1.
  filename: 'GenerateCSV',
  useTextFile: false,
  useBom: true,
  useKeysAsHeaders: true};

  const csvExporter_two = new ExportToCsv(table_two_options);
  csvExporter_two.generateCsv(data_two);

这将生成以下csv文件GenerateCSV.csv

这样,可以使用export-to-csv在单个csv文件中添加多个表
有关export-to-csv npm软件包的完整说明,请参阅export-to-csv
希望这有帮助!

相关问题