简体   繁体   中英

Parse the data read from csv file with Nodejs ExcelJS package

With NodeJs I need to fill the Excel file with the data fetched from the csv file. I am using the ExcelJS npm package.

I sucessfully read the data from csv fiel and write it in console.log() but the problem is, it is very strange format.

Code:

var Excel = require("exceljs");

exports.generateExcel = async () => {
  let workbookNew = new Excel.Workbook();

  let data = await workbookNew.csv.readFile("./utilities/file.csv");

  const worksheet = workbookNew.worksheets[0];

  worksheet.eachRow(function (row: any, rowNumber: number) {
    console.log(JSON.stringify(row.values));
  });

};

Data looks like this:

[null,"Users;1;"]
[null,"name1;2;"]
[null,"name2;3;"]
[null,"name3;4;"]
[null,"Classes;5;"]
[null,"class1;6;"]
[null,"class2;7;"]
[null,"class3;8;"]
[null,"Teachers;9;"]
[null,"teacher1;10;"]
[null,"teacher2;11;"]
[null,"Grades;12;"]
[null,"grade1;13;"]
[null,"grade2;14;"]
[null,"grade3;15;"]

So the Excel file which I need to fill with this data is very complex.. In specific cells I need to insert the users, in other sheet I need some images with grades, etc...

The Main question for me is: How can I parse and store the data which is displayed in my console.log() in separate variables like Users in separate variable, Grades in separate variable and Teachers in separate variable.

Example for users:

  users = {
    title: "Users",
    names: ["name1", "name2", "name3"],
  };

There is no need to be exactly the same as example, but the something that can be reused when I will read different csv files with same structure and so I could easily access to the specific data and put it in specific cell in the Excel file.

Thank you very much.

I prepared example, how could you pare your file. As it was proposed in one answer above we use fast-csv. The parsing is quite simple you split by separator and than took line[0] which is first element.

const fs = require('fs');
const csv = require('@fast-csv/parse');

fs.createReadStream('Test_12345.csv')
    .pipe(csv.parse())
    .on('error', error => console.error(error))
    .on('data', function (row) {
        var line = String(row)
        line = line.split(';')
        console.log(`${line[0]}`)
        
        })
    .on('end', rowCount => console.log(`Parsed ${rowCount} rows`));

If we put for input like this:

Value1;1101;
Value2;2202;
Value3;3303;
Value4;4404;

your output is in this case like this:

Value1
Value2
Value3
Value4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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