简体   繁体   English

如何从nodejs的csv文件中按列读取数据?

[英]How to read data columnwise from csv file in nodejs?

I've used the 'fast-csv' module to parse the csv file for other manipulations, but that returns data row-wise. 我使用了“ fast-csv”模块来解析csv文件以进行其他操作,但这会按行返回数据。 I want to read the first 2 columns of a csv file. 我想阅读csv文件的前2列。 Can someone please help? 有人可以帮忙吗?

I see two options. 我看到两个选择。

One is do specify which headers you want in fast-csv and discard the rest. 一种是在fast-csv指定要使用的标头,然后丢弃其余标头。 This approach will return an object which may suit your needs or you can then turn that into an array afterwards. 这种方法将返回一个可能满足您需要的对象,或者您之后可以将其转换为数组。

const csv = require('fast-csv')

const CSV_STRING = 'a,b,c\n' +
                     'a1,b1,c1\n' +
                     'a2,b2,c2\n'

let filtered = []
csv
  .fromString(CSV_STRING, { headers: ['column_1', 'column_2'], renameHeaders: true, discardUnmappedColumns: true }) // I give arbitrary names to the first two columns - use whatever make sense
  // .fromString(CSV_STRING, { headers: ['column_1', undefined, 'column_3'], discardUnmappedColumns: true }) // I could use undefined if I wanted to say skip column 2 and just want 1 and 3
  .on('data', function (data) {
    // console.log([data.column_1, data.column_2])
    filtered.push([data.column_1, data.column_2]) // or you can push to an array
  })
  .on('end', function () {
    console.log('done')
    console.log(filtered)
  })

The other is to return as an array (default) and filter what you need using the transform method 另一种是作为数组返回(默认)并使用transform方法过滤所需的内容

const csv = require('fast-csv')

const CSV_STRING = 'a,b,c\n' +
                     'a1,b1,c1\n' +
                     'a2,b2,c2\n'

csv
  .fromString(CSV_STRING)
  .transform(function (data) {
    return [data[0], data[1]]
  })
  .on('data', function (data) {
    console.log(data)
  })
  .on('end', function () {
    console.log('done')
  })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM