Generate a JSON object for every row of data in an Excel spreadsheet

Currently, I am delving into webpack for SheetJS. My experience with webpack is still growing, and I'm a complete novice when it comes to SheetJS. Rather than just getting back one JSON object containing all the Excel data, my goal is to retrieve one JSON object for every row of data in the Excel sheet.

Here's an example of the input excel layout:

Col1     Col2      Col3
A2       B2        C2
A3       B3        C3

In this scenario, the desired output would consist of 2 JSON objects:

JSON 1:

{   
 "A2": [
        {
           "Col1": "A2"
           "Col2": "B2"
           "Col3": "C2"
        }
    ]
}

JSON 2:

 {   
    "A3": [
        {
           "Col1": "A3"
           "Col2": "B3"
           "Col3": "C3"
        }
    ]
 }

This is what I've tried so far:

var to_json_linebyline = function to_json_linebyline(wb){
    var sheet = wb.Sheets['Sheet1'];
    var result = {};
    var row, rowNum, colNum;
    var range = XLSX.utils.decode_range(sheet['!ref']);
    for(rowNum = range.s.r; rowNum <= range.e.r-2; rowNum++){
    row = [];
       for(colNum=range.s.c; colNum<=range.e.c; colNum++){
          var nextCell = sheet[
          XLSX.utils.encode_cell({r: rowNum, c: colNum})
       ];
       if( typeof nextCell === 'undefined' ){
          row.push(void 0);
       } else row.push(nextCell.w);
       }
       result[nextCell.v] = row;
    }
    return JSON.stringify(result, 2, 2); 
}

The current outcome looks like this:

{
  "Col3": [
    "Col1",
    "Col2",
    "Col3"
  ],
  "C2": [
    "A2",
    "B2",
    "C2"
  ],
  "C3": [
    "A3",
    "B3",
    "C3"
  ]
}

I would greatly appreciate any guidance or assistance pointing me in the right direction. For further reference, you can access the GitHub repository. Thank you!

Answer №1

Your approach is correct but the code needs some adjustments. Instead of inserting data into arrays, you should be creating a JSON object. Here's the revised version:

var to_json_linebyline = function to_json_linebyline(wb){
    var sheet = wb.Sheets['Sheet1'];
    var results = [];
    var range = XLSX.utils.decode_range(sheet['!ref']);
    for(let rowNum = (range.s.r+1); rowNum <= range.e.r; rowNum++){
       let thisRow = {},
           thisNode = '';
       
       for(let colNum=range.s.c; colNum<=range.e.c; colNum++){
          var thisHeader = sheet[XLSX.utils.encode_cell({r: 0, c: colNum})].w
          var thisCell = sheet[XLSX.utils.encode_cell({r: rowNum, c: colNum})].w
          if(colNum === 0){ 
            thisNode = thisCell;
          }
          thisRow[thisHeader] = thisCell;
       }
       thisResult = {};
       thisResult[thisNode] = [thisRow]
       results.push(thisResult)
    }
    return JSON.stringify(results);
}

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

Issue with retrieving duration XML data using Jquery

Could there be a specific explanation as to why the term duration might not function properly in JQuery? For instance, consider this XML snippet: <video description="description etc" duration="43306" id="1144537378001" name="Fashion" thumbnail="http:// ...

I'm having trouble understanding the difference between JSONObject and JSON string when it comes to reading JSON in android. Can anyone provide

I am struggling to differentiate between a JSON Object and a JSON String. Can you help clarify which part constitutes a JSON Object, and which represents a JSON String? JSON sample 1: { "abc": "v1", "def": "v2" } JSON sample 2: { "res": ...

Error message "The function is being called from the parent but is undefined"

Although there are numerous questions on stackoverflow with accepted answers, I haven't been able to find the specific one I'm looking for. In my scenario, I have a parent HTML file importing another HTML from it. I am fetching a list in the par ...

dynamically display elements within aframe based on specific conditions

In my aframe scene, there are three icosahedrons, a complex particle system, and a cursor that fuses on objects within the scene. The performance of the scene is affected when the particles are visible because the cursor attempts to fuse with every particl ...

When a decimal of 0.02 is added to a number in javascript, it may lead to

I am attempting to create an array of numbers ranging from a specific minimum value to a certain maximum value with a specified decimal interval, such as 0.02. For instance, the sequence would be like: 1.00, 1.02, 1.04, 1.06 The issue arises when the code ...

Expect for a variety of Observables to finish at different times

I am faced with the challenge of extracting data from an API that is paginated, and unfortunately, I cannot determine the total number of pages in advance. However, I can identify when I have reached the last page. My goal is to develop a function that ret ...

Guide to dynamically assigning the id attribute of an HTML element using angularjs (1.x)

Given an HTML element that is a div, what is the method to assign a value to its id attribute? The value should be a combination of a scope variable and a string. ...

Comparing Jquery's smoothscroll feature with dynamic height implementation

Recently I launched my own website and incorporated a smoothscroll script. While everything seems to be working smoothly, I encountered an issue when trying to adjust the height of the header upon clicking on a menu item. My dilemma is as follows: It appe ...

What is the best way to render JSON information in JSP with JavaScript?

Using Spring MVC, my controller "Book.java" returns a JSON object. I would like to display the content of the JSON object in a table format in a JSP. How can I achieve this? Here is the function in my controller that returns the JSON object: @Controller ...

What is the best way to target the shadow DOM host element specifically when it is the last child in the selection?

I want to style the shadow DOM host element as the last child. In this particular situation, they are currently all green. I would like them to be all red, with the exception of the final one. class MyCustomElement extends HTMLElement { constructor() ...

Conflicts arising between smoothState.js and other plugins

After successfully implementing the smoothState.js plugin on my website, I encountered an issue with another simple jQuery plugin. The plugin begins with: $(document).ready() Unfortunately, this plugin does not work unless I refresh the page. I have gone ...

transmit information to a FLUTTER server

I attempted to follow the instructions provided at in order to send data, but unfortunately, my code is not functioning as expected. I am unsure of what the issue may be. Could someone please assist me by pointing out any errors or recommending a helpful ...

Error Occurred: ngRepeat directive encountered an invalid expression while attempting to render the

HTML <tr ng-repeat="sale as examples"> <td class="text-right"> @{{sale.sales_person}}</td> <td class="text-right"> @{{sale.sales_total}}</td> <td class="text-right"> @{{sale.sales_target_amount}}</td> ...

Loading javascript libraries that are contained within an appended SVG document

I am currently working on developing a browser-based SVG rasterizer. The unique aspect of this project is that the SVG files may contain JavaScript code that directly impacts the output, such as randomly changing element colors, and utilizes external libra ...

Featuring a visual arrangement of categorized images with AngularJS for an interactive display

As I work on developing a web application with Angular, my goal is to create a grid layout that organizes items by category. Each row will represent a different category. Below is an example of the code structure I have in place: <ion-item ng-repeat="i ...

Using TypeScript to dynamically assign types to object properties

As a newcomer to TypeScript, I am in the process of migrating some of my custom components/plugins to TS. One of the challenges I'm facing is setting object properties dynamically when the property name is a variable. I would greatly appreciate a be ...

Converting a list into a JSON string using Thymeleaf and the Spring Boot converter

Currently, I am developing a service that generates HTML pages using Thymeleaf templates. In one of these templates, I need an HTML attribute to be represented as a JSON string. The object related to this in my context is an ArrayList<String>. By def ...

The integration of socket.io with static file routing in node.js is encountering issues

I am currently developing a chat application and I have encountered an issue. When the static file routing is functioning correctly, the socket.io for the chat feature throws a "not found" error in the console. http://localhost/socket.io/?EIO=3&tran ...

Exploring MongoDB through proxyquire

To simulate a MongoDB dependency using proxyquire in my testing scenario, I have the following code snippet: var proxyquire = require('proxyquire'); var controller = path.resolve('.path/to/controller/file.js'); inside the before each ...

Having trouble bypassing the alert in Google Chrome after automatically logging into Facebook using selenium-webdriver. I am using Javascript / JS language

const {Builder, By, Key} = require('selenium-webdriver'); const {Options} = require('selenium-webdriver/chrome'); const options = new Options().setAlertBehavior('dismiss'); let driver = new Builder().forBrowser('chrome&a ...