如何将列表作为节点js中的列写入csv文件中?

时间:2018-07-10 11:36:46

标签: node.js csv

const fs = require('fs');
const csv = require('fast-csv');

let ws = fs.createWriteStream('/Users/emreakyol/Desktop/column.csv');

let part1 = ["C1R1", "C1R2", "C1R3"];
let part2 = ["C2R1", "C2R2", "C2R3"];
let part3 = ["C3R1", "C3R2", "C3R3"];
csv.
    write([
        part1,
        part2,
        part3
    ], {headers:true})
        .pipe(ws);

我想在my.csv文件中看到类似的内容。 输出(my.csv文件):

C1R1 C2R1 C3R1
C1R2 C2R2 C3R2
C1R3 C2R3 C3R3

我看到了有关fast-csv库的“数组数组”,但是我找不到如何使用它。 https://www.npmjs.com/package/fast-csv

1 个答案:

答案 0 :(得分:2)

从github问题来看,此功能不起作用(仅报告,无响应)。

使用问题中提供的语法,我们将数组插入为行。您想插入数组作为行列,因此解决方法是某种映射函数,例如。 (我已经修改了您的代码)

let part1 = ["C1R1", "C1R2", "C1R3"];
let part2 = ["C2R1", "C2R2", "C2R3"];
let part3 = ["C3R1", "C3R2", "C3R3"];
let parts = [part1, part2, part3];
parts = parts.map((part, index) => {
  let newPart = [];
  [...Array(part.length).keys()].forEach((iterator, innerIndex) => newPart.push(parts[innerIndex][index]))
  return newPart;
})
csv.write(parts, {headers:true})