Export data to CSV (Excel) with NodeJs and React

Posted: 28-12-2021 | Views: 231
Export data to CSV (Excel) with NodeJs and React

BACKEND - NodeJs

router.js

var { Parser } = require('json2csv');
const dataService = require('../service');

router.get('/exportData', cors(), async (req, res) => {
    const list = await dataService.getData(req);
    const fields = [
        { label: 'Id', value: 'Id' },
        { label: 'Name', value: 'Name' },
        { label: 'Age', value: 'Age' },
        { label: 'Date', value: 'Date' },
    ];
    const json2csv = new Parser({ fields: fields });
    const csv = json2csv.parse(list);
    res.status(200).send(Buffer.from(csv));
});

service.js

const { ExampleModel } = require("../models");

exports.getData = async (req) => {
    let list = [];
    try {
        const request = {
            where: {}
        };

        list = JSON.parse(JSON.stringify(await ExampleModel.findAll(request)));

    } catch (error) {
        console.log(error);
    }
    return list;
}

FRONT END - REACT

app.js

import download from "downloadjs";
import Axios from "axios";

async function exportResultToExcel() {
    try {
        let filters = { ...this.state.filter };
        const res = (await Axios.get(`api/exportData`, {
            params: filters,
            responseType: "blob"
        })).data;
        if (res) {
            download(res, new Date().toLocaleDateString() + '-data.csv');
        } else {
            alert("Data not found");
        }
    } catch (error) {
        console.log(error);
    }
}

<Button onClick={() => { this.exportResultToExcel() }}>Export to CSV</Button>

Add comment