'How can I export a JSON object to Excel using Nextjs/React?

I have an endpoint that retrieves a json object like the following:

"data": [
{
"id": 1,
"temaIndicador": "Indian",
"codigo": "001",
"observaciones": "Interactions Specialist tertiary Regional Tennessee",
"activo": "SI",
"urlImagen": "http://placeimg.com/640/480",
"color": "cyan",
"createdAt": "2022-01-26T18:48:36.002Z"
]

And I want to implement a button that will allow the user to export the data to multiple formats, including Excel (.xlsx) but I don't really know were to start. I've already seen libraries that realize this, but I don't feel comfortable because they usually have less than 1.5k downloads per week.

My purpose is to export an Excel document with a simple table where the headers are going to be the attributes of the objects.



Solution 1:[1]

Use xlsx third-party library.

npm install xlsx

Using Library:

import XLSX from "xlsx";

Download function trigger at button click(pass data as argument):

downloadExcel = (data) => {
    const worksheet = XLSX.utils.json_to_sheet(data);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
    //let buffer = XLSX.write(workbook, { bookType: "xlsx", type: "buffer" });
    //XLSX.write(workbook, { bookType: "xlsx", type: "binary" });
    XLSX.writeFile(workbook, "DataSheet.xlsx");
  };

Download Button: (function call: you should modify it as per your requirement, below one is React Class Component implementation, that's why I used this )

<button onClick={()=>this.downloadExcel(data)}>
    Download As Excel
</button>

Solution 2:[2]

Based on the accepted answer, in case someone is getting the "Attempted import error: 'xlsx' does not contain a default export (imported as 'XLSX')" error, try importing using the following:

import * as XLSX from 'xlsx';

Hope it helps.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Manuel Contreras