Learn the process of retrieving JSON data in an Excel file using the json_to_sheet function

I am currently working on populating an excel file by utilizing the JSON data provided below. This JSON data is retrieved from an HTTP response and I intend to utilize it for downloading an excel file.

   {  
       "dynaModel":[  
          {  
             "map":{  
                "UNIT/SUBUNIT":"sdasd",
                "SUBUNIT/ISU/GEO":"sasd",
                "REVENUEINR-RS":"₹87,sdd",
                "COSTINR-RS":"₹47,33",
                "GMINR-RSUSD-$":46,
                "REVENUEINR-RS":"₹87,64,",
                "COSTINR-RS":"₹47,33,",
                "GMINR-RSUSD-$":46
             }
          },
          {  
             "map":{  
                "UNIT/SUBUNIT":"fghf",
                "SUBUNIT/ISU/GEO":"CMghhfI",
                "REVENUEINR-RS":"₹59,06",
                "COSTINR-RS":"₹30,43",
                "GMINR-RSUSD-$":48.47,
                "REVENUEINR-RS":"₹59",
                "COSTINR-RS":"₹30,43",
                "GMINR-RSUSD-$":48.47
             }
          },
          {  
             "map":{  
                "UNIT/SUBUNIT":"hfgh",
                "SUBUNIT/ISU/GEO":"fghh",
                "'APR-16'_REVENUEINR-RS":"₹29,72",
                "'APR-16'_COSTINR-RS":"₹11,43",
                "'APR-16'_GMINR-RSUSD-$":61.53,
                "'Total'_REVENUEINR-RS":"₹29,72",
                "'Total'_COSTINR-RS":"₹11,43",
                "'Total'_GMINR-RSUSD-$":61.53
             }
          }
       ]
   }

The code snippet of my components can be seen below:

excelDownload(){
   this._isuGeoSubunitReportService.excelDownload(this.isugeosubunitTO)
    .subscribe(data =>this.responseStatus = data,
        err => console.log(err),
       () => console.log('Request Completed')
    );

const ws_name = 'SomeSheet';  
const wb: WorkBook = { SheetNames: [], Sheets: {} };
const ws: any = utils.json_to_sheet(this.responseStatus.dynamoModel);
wb.SheetNames.push(ws_name);
wb.Sheets[ws_name] = ws;
const wbout = write(wb, { bookType: 'xlsx', bookSST: true, type: 'binary' });

function s2ab(s) {
  const buf = new ArrayBuffer(s.length);
  const view = new Uint8Array(buf);
  for (let i = 0; i !== s.length; ++i) {
    view[i] = s.charCodeAt(i) & 0xFF;
  };
  return buf;
}

saveAs(new Blob([s2ab(wbout)], { type: 'application/octet-stream' }), 'exported.xlsx');
}

I am attempting to download the result in xlsx format using the xlsx module of json. While it works well for simple JSON data, I am encountering challenges with my complex JSON data.

   const ws: any = utils.json_to_sheet(this.responseStatus);

If I directly use this.responseStatus, only one map value is returned in the excel sheet.

Answer №1

There seems to be a typo in your code where you are using: this.responseStatus.dynamoModel instead of this.responseStatus.dynaModel.

Additionally, as per the documentation for the module xlsx, the array you are trying to parse should have a structure similar to this before utilizing utils.json_to_sheet:

[
  {S:1,h:2,e:3,e_1:4,t:5,J:6,S_1:7},
  {S:2,h:3,e:4,e_1:5,t:6,J:7,S_1:8}
]

You can use the function utils.aoa_to_sheet instead of utils.json_to_sheet.

Alternatively, you have the option to create a custom function that will restructure your data to match the format specified in the documentation for utils.json_to_sheet. Here's how I modified the code in your component:

excelDownload() {
    this.appService.excelDownload()
      .subscribe(data => {
          this.responseStatus = data;
          this.generateExcelFile(data);
        },
        err => console.log(err),
        () => console.log('Request Completed222')
      );
  }
  generateExcelFile(data: any) {
    this.responseStatus = data;
    const ws_name = 'SomeSheet';
    const wb: WorkBook = { SheetNames: [], Sheets: {} };
      const ws: any = utils.json_to_sheet(parseArray(this.responseStatus.dynaModel));
    wb.SheetNames.push(ws_name);
    wb.Sheets[ws_name] = ws;
    const wbout = write(wb, { bookType: 'xlsx', bookSST: true, type: 'binary' });

    function s2ab(s) {
      const buf = new ArrayBuffer(s.length);
      const view = new Uint8Array(buf);
      for (let i = 0; i !== s.length; ++i) {
        view[i] = s.charCodeAt(i) & 0xFF;
      }
      return buf;
    }
    // function to parse your array coming from the backend 
    function parseArray(dataToParse: any) {
      const newArray = [];
      dataToParse.forEach(item => {
        Object.keys(item).forEach(key => {
          newArray.push(item[key]);
        });
      });
      console.log('newArray:' + JSON.stringify(newArray));
      return newArray;
    }

    FileSaver.saveAs(new Blob([s2ab(wbout)],
      { type: 'application/octet-stream'}),
      'exported.xlsx');
  }

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

Place content following a three.js display created within a <div id="mainWindow">

Recently, I created a small Three.js animation and embedded it in my HTML page like this: <div id="mainWindow" class="popup_block"> <!-- JavaScript for simulation --> <script src="../temp/webgl-debug.js"></script> <scri ...

A TypeScript class transferring data to a different class

I have a set of class values that I need to store in another class. function retainValues(data1,data2){ this.first = data1; this.second = data2; } I am looking for a way to save these class values in a different class like this -> let other = N ...

Show images exclusively on screens with a smaller resolution

Looking for assistance in modifying the code below to only display the image in mobile view, instead of constantly appearing. <style type="text/javascript> .icon-xyz {float: left; width: 22px;cursor: pointer;background: none;} @me ...

Adding a total property at the row level in JavaScript

Here is a JavaScript array that I need help with: [{ Year:2000, Jan:1, Feb: }, {Year:2001, Jan:-1, Feb:0.34 }] I want to calculate the total of Jan and Feb for each entry in the existing array and add it as a new property. For example: [{ Year:2000, Ja ...

Implementing jQuery to easily upload and display images

Discover a handy jQuery script that enables you to preview an image before uploading it. <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <scrip ...

Experiencing erratic outcomes with window.innerWidth in Mobile Safari

I am currently using JavaScript to determine the width of the browser: $(document).ready(function(){ var width = window.innerWidth; }); However, it seems that this method is producing inconsistent results. To showcase the issue, I have created a fun ...

A guide on iterating through an array to extract the initial character from every string

Currently, my focus is on extracting the initial letter of each word in order to create an acronym. I have set up an array where all the capitalized words are stored, and now I need a way to extract those specific characters. To achieve this, I initially ...

Transferring the Header component from standard React to Gatsby: Eliminating Duplicates

After initially creating a front-end using create-react-app, I decided to transfer it to Gatsby.js. However, I encountered an issue where the component Header.js was being displayed multiple times. Can anyone explain why this would happen? https://i.sstat ...

JSONPath - select only the fields with names containing "@" symbol

I am in possession of a JSON structure that looks like this: { "media": { "@ref": "https://Bull_FTR.mpg", "track": [{ "@type": "General", "VideoCount": "1" }, { "@type": "Video", ...

The geometry map in THREE.js fails to render

https://i.sstatic.net/1q45u.jpg Next, I am loading an image map onto a custom geometry that represents the brown-colored shape in the image above: var aqua_ground_geo = new THREE.Geometry(); var top0 = new THREE.Vector3(aqua_ground_geo_x_NEG, user_data[ ...

How does jQuery create a hover effect that changes the background color of a link and keeps it when the mouse hovers over a

I'm attempting to add a background color to the main link that displays a sub-menu. Currently, only the sub-menu is visible, and as soon as the mouse moves away from the main link, the color reverts back to the original background color. <nav& ...

Dealing with Angular routes in Express: Solving the issue of "res.sendFile is not a function"

I am facing an issue with my angular app running on a node server and serving static files. The app works perfectly fine when accessed from http://localhost:3000 and all angular routes function as expected. However, when I directly enter an address with an ...

Tips for troubleshooting a Typescript application built with Angular 2

What is the best approach for debugging an Angular 2 Typescript application using Visual Studio Code or other developer tools? ...

prolonging inner interface created by supabase

Below is the Typescript interface that has been generated by Supabase export interface definitions { Users: { /** Format: uuid */ id: string; /** * Format: timestamp with time zone * @default now() */ created_at?: string; ...

Using the getAttribute method in Edge with JavaScript

My goal is to dynamically load videos on the page after it has fully loaded. I have a script that successfully works in Firefox and Chrome, but I encounter errors when using Edge/IE. The specific error message I receive is SCRIPT5007: Unable to get propert ...

Expanding Submenu Width

Currently working on developing a Dynamic Sub-menu for Wordpress, similar to the one shown here: . However, I am facing an issue with the width as it is set to 'auto' but not aligning the sub-menu properly. I would like the sub-menus to float lef ...

Unable to fetch all data from the Json file

I have been retrieving JSON data from and then displaying the titles in a ListView. The code seems to be functioning correctly, but I am facing a challenge where some titles are getting skipped in my ListView and one particular title is being repeated. I ...

Parsing an XML array using XSLT and implementing a universal template for nested elements to convert from XML to JSON

My task involves converting a number of XML files into the appropriate JSON format using XSLT. While I've managed to convert everything successfully, one issue remains with arrays. I need to create templates that are versatile enough to handle any sce ...

Steps for establishing a connection to a MongoDB database on Heroku using mongoose

Everything is running smoothly with my app locally and it can successfully connect to the local database. However, when I attempt to run it on Heroku, I encounter the following error: 2014-04-17T06:32:23.404458+00:00 app[web.1]: > <a href="/cdn-cgi ...

Having trouble with Next-Auth's signIn with Credentials feature in NextJS?

I have recently added the next-auth package to my new Next.js project. Despite following all the documentation for both Next.js and next-auth, I am still unable to resolve the issue. The problem I am encountering is as follows: I am trying to log in to my ...