How can I convert an xlsx file to JSON using ExcelJS in Node.js?

https://github.com/guyonroche/exceljs

I am a beginner with exceljs and just came across the description of exceljs on github.

The description states: "Read, manipulate and write spreadsheet data and styles to XLSX and JSON."

I am looking for a way to convert a workbook into a JSON object in exceljs, but I couldn't find any method or module similar to what is available for csv files.

Please let me know if there is such a feature available in exceljs.

Answer №1

Although this question may seem dated, I want to contribute an answer for anyone who finds themselves in a similar situation now.

A solution does exist.

I too was searching for the same information as you, but initially came up empty-handed. However, after some thorough investigation, I discovered a method to achieve it.

import Exceljs from 'exceljs';

const workbook = new Exceljs.Workbook();
await workbook.xlsx.load(data);
const json = JSON.stringify(workbook.model);
console.log(json); // shows the json object

I combined insights from this forum post and referenced Exceljs' documentation to unlock the solution. Hopefully, this explanation proves helpful to others.

Answer №2

Extracting data from an Excel file can be easily accomplished using the exceljs library.

const ourData = [];
workbook.eachSheet( sheet => {
  const currentSheet = [];
  worksheet.eachRow(row => {
    currentSheet.push(row.values);
  });
ourData.push(currentSheet);
});

It's important to note that array indexes for cells typically start at 1.

Answer №3

    // processing Excel data
    let sheetTitles = [];
    let sheetData = [];

    // converting Excel to JSON (only first sheet)
    workbook.worksheets[0].eachRow((row, rowNumber) => {
        // skip empty rows
        if (rowNumber > 0) {
            let rowData = row.values;
            rowData.shift(); // remove extra element

            if (rowNumber === 1) sheetTitles = rowData;
            else {
                let rowObj = {}
                for (let j = 0; j < sheetTitles.length; j++) {
                    let titleName = sheetTitles[j];
                    let cellValue = rowData[j] ? rowData[j] : '';
                    rowObj[titleName] = cellValue;
                }
                sheetData.push(rowObj);
            }
        }
    })
    console.log(sheetData);
    return;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to Show the Contents of the Item - AngularJS

I'm in the process of developing an application that will showcase job details within a modal window based on the selected template. To achieve this, I've integrated ui.bootstrap and ui.router. However, I'm encountering difficulties in displ ...

Utilizing Weather APIs to fetch JSON data

Trying to integrate with the Open Weather API: Check out this snippet of javascript code: $(document).ready(function() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { $(".ok").html("latitude: " + ...

Troubleshooting JavaScript Date Problem with Internet Explorer 7

When I retrieve a Date from a web method, it comes in the format of "Mon Sep 30 07:26:14 EDT 2013". However, when I try to format this date in my JavaScript code like this: var d= SomeDate.format("MM/dd/yyyy hh:mm:ss tt"); //Somedate is coming from the we ...

Decoding JSON on 9gag

I am trying to select a random image from the following URL: In order to display it correctly, I need to determine the size of the image. I am utilizing YQL to store the JSON result in a variable (referred to as source). After replacing 'https&apos ...

Automatically populate the options of a dropdown menu using jQuery

I am a beginner in the world of Javascript, JSON, and jQuery. I am seeking some guidance as I navigate through this new territory. On my JSP page, there is a drop down list that needs to be populated with content when the page loads. To achieve this, I hav ...

How to convert an array of keys and an array of values into an array of objects using JavaScript

My question is similar to the one found here: Merging keys array and values array into an object using JavaScript However, I am unable to find a solution for my specific scenario. If I have these two arrays: const keys = ['x', 'y', &ap ...

Understanding the JSON output received from the Servlet

So, I have a Java Servlet set up to return JSON data in Application/JSON format using the GSON library. The GET method of the Servlet requires an ID parameter. When I send a request with BookingID as 1, Chrome shows the AJAX response like this: 0: {W ...

Defining JSON Schema for an array containing tuples

Any assistance is greatly appreciated. I'm a newcomer to JSON and JSON schema. I attempted to create a JSON schema for an array of tuples but it's not validating multiple records like a loop for all similar types of tuples. Below is a JSON sampl ...

The image fails to load when attempting to retrieve it from a local JSON file

I successfully managed to fetch data dynamically from a local JSON file created in RN. However, when I tried to add images for each profile to be displayed along with the dynamic profile info, the app encountered an error stating that "The component cannot ...

What distinguishes {key:" "} from {key:" "}, when it comes to JSON files?

I have been working on implementing validation using express Router. The issue I encountered is that when I pass {title:""}, the express-validator does not throw an error. However, when I pass {title:" "}, it works properly. exports.postValidatorCheck = [ ...

Making a XMLHttpRequest/ajax request to set the Content-Type header

In my attempts, I have tested the following methods individually: Please note: The variable "url" contains an HTTPS URL and "jsonString" contains a valid JSON string. var request = new XMLHttpRequest(); try{ request.open("POST", url); request.set ...

Using ExtJS to populate a panel with data from various sources

I am currently working with an Ext.grid.GridPanel that is connected to a Ext.data.JsonStore for data and Ext.grid.ColumnModel for grid specifications. Out of the 10 columns in my grid, 9 are being populated by the json store without any issues. However, I ...

"Discrepancy in results between JSON stringify and JavaScript object conversion

I need to save this object in a database, but first I have to send it to the backend. Recorder {config: Object, recording: false, callbacks: Object, context: AudioContext, node: ScriptProcessorNode…} However, after using JSON.stringify(recorder) The r ...

Implementing Node.JS ajax to update current JSON information

I am seeking assistance in updating data within a JSON file using NODE.JS. Currently, my method adds the data with the same ID as expected. However, upon receiving the data back, it eliminates the last duplicate because it encounters the old value first. I ...

Issue Encountered with FabricJS: Unable to Execute 'drawImage' with Image Subclass

I'm working on a project that requires me to add images of different types to a canvas, save them as JSON, and then load them again. The unique property needed for each type is simply the differentiation in type. To achieve this, I have created a new ...

Unable to retrieve data from the JSON file after making a $http.post call

Currently facing an issue with my grocery list item app developed in AngularJS. I have simulated a connection to a server via AJAX requests made to local JSON files. One of the files returns a fake server status like this: [{ "status": 1 }] I am att ...

Show only specific data from JSON results

I am trying to display a specific cryptocurrency's price without the need for curly braces or explicitly stating "USD". Currently, it appears as {"USD":0.4823} when using the following code: <script> $(document).ready(function () { ...

What is the best way to extract all of the JSON data from Firebase using a web platform?

As a newcomer to Firebase and noSQL databases, I'm encountering difficulties in extracting all the JSON data from the database. Although I've gone through the firecast tutorials and understand how to retrieve specific values by referencing the da ...

Tips for retrieving information from a highstock chart

Imagine I have a sample highstock chart on my website, similar to the one at this link. Is there a way to extract the data from the chart itself, even if the data used for creating the chart is not accessible to others? <img src="http://www.highchart ...

Harnessing the Power of Google Apps Scripts: Mastering the Art of Handling Comma-Separated Spreadsheet Values Transformed

I have a spreadsheet where column 1 contains source file IDs, with each cell holding only one ID. Column 2 has destination file IDs, where cells contain multiple IDs separated by commas. I utilize a script to retrieve these values and perform various opera ...