skip to Main Content

here I’m converting json to csv now i want to convert this csv file to xlsx data and upload it to AWS and get the link

Convert CSV to XLSX
const xlsxFilePath = 'path/to/transaction_data.xlsx';
await csvtoxlsx.writeToFile(xlsxFilePath, csvData);

Read the XLSX file
const fileContent = fs.readFileSync(xlsxFilePath);

I’m getting an error in writeToFile and cannot install the npm package csvtoxlsx.

2

Answers


  1. Chosen as BEST ANSWER
    exports.convertArrayToCSV = (data, headers) => {
    const csvRows = [];
    const headerValues = headers.map((header) => header.label);
    csvRows.push(headerValues.join(","));
    data.forEach((object) => {
    const values = headers.map((header) => {
      if (typeof header.value === "function") {
        return header.value(object);
      }
      return object[header.value];
    });
    csvRows.push(values.join(","));
    });
    const csvData = csvRows.join("n");
    return csvData;
    };
    let fileName = `Transaction_report_${req?.headers?.daterange}`;
    
        const csvData = convertArrayToCSV(
          data?.data?.transactions,
          downloadFields
        );
        console.log(csvData, "csvDATA");
         
        const workbook = xlsx.utils.book_new();
        const worksheet = xlsx.utils.aoa_to_sheet([]);
    
        const rows = [];
        let hasHeader = false;
        streamifier
          .createReadStream(csvData)
          .pipe(csv())
          .on("data", (data) => {
            if (!hasHeader) {
              const headerRow = Object.keys(data);
              console.log(headerRow, "asjhgdghasdh");
              xlsx.utils.sheet_add_aoa(worksheet, [headerRow], {
                origin: 0,
              });
              hasHeader = true;
            }
            const rowData = Object.values(data);
            console.log(rowData, "asdahjsd");
            rows.push(rowData);
          })
          .on("end", () => {
            xlsx.utils.sheet_add_aoa(worksheet, rows, { origin: 1 });
            xlsx.utils.book_append_sheet(workbook, worksheet, "Sheet 1");
    
            const outputFilePath = "output1254.xlsx";
            xlsx.writeFile(workbook, outputFilePath);
            console.log("Conversion complete!");
          });
    

  2. Try with those new packages.

    npm install csvtojson xlsx

    const csv = require('csvtojson');
    const XLSX = require('xlsx');
    
    app.get('/api/csv-to-xlsx', async (req, res) => {
      try {
        const csvFilePath = '/path/to/your/csv/file.csv'; // Replace with the actual path to your CSV file
        const jsonArray = await csv().fromFile(csvFilePath);
        const workbook = XLSX.utils.book_new();
        const worksheet = XLSX.utils.json_to_sheet(jsonArray);
        XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
        const xlsxFilePath = '/path/to/save/xlsx/file.xlsx'; // Replace with the desired path to save the XLSX file
        XLSX.writeFile(workbook, xlsxFilePath);
    
        // Upload to S3 in here
    
        res.status(200).json({ success: true, message: 'CSV to XLSX conversion completed' });
      } catch (error) {
        console.log(error);
        res.status(500).json({ success: false, error: 'An error occurred during conversion' });
      }
    });
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search