Skipping certain key-value pairs during the conversion from JSON to Excel Worksheet using the XLSX library in JavaScript

I have a set of objects in JSON format within my JavaScript code and I am looking to transform this data into an Excel worksheet. Within the JSON structure, there are certain key-value pairs that I do not wish to include in the Excel output. For instance, I want to exclude any information related to the year as shown below (PLEASE EXECUTE HTML CODE TO VIEW DESIRED EXCEL OUTPUT):

JSON example:

[
  {
    car: "Range Rover",
    color: "silver",
    year: "2021"
  },
  
  {
    car: "Benz",
    color: "black",
    year: "2019"
  },
  
  {
    car: "Toyota",
    color: "silver",
    year: "2020"
  }
]

Desired Excel view (Execute snippet):

<html>
  <body>
    <table>
      <tr>
        <th>car</th>
        <th>color</th>
      </tr>

      <tr>
        <td>Range Rover</td>
        <td>silver</td>
      </tr>

      <tr>
        <td>Benz</td>
        <td>black</td>
      </tr>

      <tr>
        <td>Toyota</td>
        <td>silver</td>
      </tr>
    </table>
  </body>
</html>

Is it possible to accomplish this using XLSX library in JavaScript?

Answer №1

There are a couple of options you have in this scenario.

  1. To manipulate your JSON data, one approach is to save it into an xlsx worksheet, modify the worksheet's !ref property to define the range you want, and then include that sheet in the xlsx book.
let file = fs.readFileSync('test.json', 'utf-8');
let data = JSON.parse(file);

var wb = xlsx.utils.book_new();
var ws = xlsx.utils.json_to_sheet(data);

ws['!ref'] = 'A1:B4';
xlsx.utils.book_append_sheet(wb, ws, 'Sheet 1');
xlsx.writeFile(wb, 'test1.xlsx');
  1. An alternate method involves filtering out specific properties from your JSON data into a separate array and then incorporating them into the file.
let file = fs.readFileSync('test.json', 'utf-8');
let data = JSON.parse(file);

var wb = xlsx.utils.book_new();

let dataArray = [];
data.forEach(d => {
  dataArray.push({"car": d.car, "color": d.color});
});

var ws = xlsx.utils.json_to_sheet(dataArray);
console.log(ws);
xlsx.utils.book_append_sheet(wb, ws, 'Sheet 1');
xlsx.writeFile(wb, 'test2.xlsx');

Referencing the utility functions documentation can also provide valuable insights.

https://www.npmjs.com/package/xlsx#utility-functions

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

Exploring test suite pathways while utilizing ArcGIS JSAPI as an alternative loader within the Intern framework

I have been developing an application using the ArcGIS Javascript API and incorporating tests with Intern. While working on Windows 7 under IIS, I encountered some challenges but managed to overcome them by following the Intern tutorial and referring to so ...

Utilizing DOMStringMap data to populate CSS URLs

I am attempting to create a universal CSS modification for a webpage element that resembles: <button data-action="link" class="cardImageContainer coveredImage cardContent itemAction lazy lazy-image-fadein-fast" data-blurhash="lo ...

"Encountering a challenge when trying to populate a partial view using AngularJs and MVC

I am a beginner in AngularJS and I'm using a partial view for Create and Edit operations, but I'm encountering issues while trying to retrieve the data. The data is successfully being retrieved from my MVC controller but it's not populating ...

javascript path as the first argument and callback as the last argument

Currently, I am in the process of creating a wrapper function for expressjs's app.get method. In these methods such as get, you can provide the path, some options, and then the callback. However, it is possible to omit the options and still have it w ...

Setting the Date in Angular.js: A Step-by-Step Guide

Make maxDate selectable as today at the latest (past days are clickable but not tomorrow). The range between minDay and maxDay should not exceed 365 days, allowing for fewer days to be selected. $scope.dateOptions = { formatYear: " ...

Enhance Your Website with Interactive Tooltips Using Twitter Bootstrap

In Twitter bootstrap, the default trigger for tooltips is hover. If I want to make the tooltip display on focus instead, I can add data-trigger="focus". But how do I make it so the tooltip displays both on hover and on focus? ...

Open the JSON file on Amazon Alexa

Currently, I am in the process of developing an app that allows users to search for flight connections using Amazon Alexa. My main challenge lies in loading a json file containing airport information into a variable to retrieve data from it at a later stag ...

What's the best way to use JavaScript to obtain the width of a 'css-pixel' based on a media query?

While there have been discussions on how to determine device sizes using media queries like Twitter Bootstrap, I am looking for a reliable way to achieve the same output using JavaScript. Specifically, I want to get the CSS media query pixel number rather ...

Learning how to replace the alert function with Bootbox

I am currently working on a form that posts to a MySQL database. I want to replace the alert function triggered by the Malsup jQuery Form Plugin with the one created by the Bootbox plugin. Even though both plugins are functional, I struggle to integrate th ...

Navigating intricate JSON information using AngularJS

I am working on displaying JSON data in an HTML form using ng-repeat. I have managed to retrieve data from some objects, but I am facing challenges due to the nested structure of objects like "Obj => Obj => Obj". In the JSON object provided below, I have ...

Can someone guide me on how to display Jade content using JSON in Node.js?

A few months back, I developed a video gallery web application using CodeIgniter. Now, I am in the process of migrating the backend to Node with Express and Jade to generate content. Previously, the PHP version sent JSON data to the frontend, which sometim ...

Change button to an ajax spinner when it is clicked using jQuery

$(".post-btn").html("<img src='../images/loader.gif' />"); Why isn't this code working? I know I have the correct selector because when I tried $(".post-btn").text('test'), it worked. I want the text of the button to change ...

Struggling with loading.jsx file in next js version 13.4.5?

Encountered an issue with loading components in next js 13.4.5 layout.jsx "use client"; import React, { Suspense } from "react"; import { ThemeProvider, createTheme } from "@mui/material/styles"; import CssBaseline from " ...

How can I verify the status of an occasional undefined JSON value?

There are times when the JSON object I'm trying to access does not exist. Error: Undefined index: movies in C:\xampp\htdocs\example\game.php In game.php, I'm attempting to retrieve it from the Steam API using this code: $ ...

How to Create a Custom Callback Function for jQuery's .html

I am currently working with the following code: $.ajax({ type: 'GET', url: 'index.php?route=checkout/onepagecheckout/getpaypaldata', dataType: 'json', success: function(json) { ...

The never-ending nightmare of acquiring a Facebook Graph token

One of the tasks I regularly undertake for clients is fetching Facebook photos to incorporate into their websites. However, I often encounter a frustrating issue where the photos work for a while and then suddenly stop working. After doing some research o ...

Is there a way to dynamically load a file on scroll using JavaScript specifically on the element <ngx-monaco-diff-editor>?

I've been attempting this task for over a week now in Angular without success. Would someone be able to provide guidance? The onContainerScroll() function isn't being triggered, and I'm considering using JavaScript instead. How can I achiev ...

How to make a straightforward task list using ExpressJS

As a beginner, I am attempting to create a basic todo list using ExpressJS. Currently, my goal is to simply display some hardcoded todos that I have in my application. However, I seem to be struggling to identify the mistake in my code. Any assistance woul ...

Looking for the location of a matching brace in a dataset?

As a newbie in the world of coding, I have embarked on learning about NodeJs file system module. Currently, my focus is on handling a large data file stored as a string. The challenge that I am facing is with locating the matching close brace and its pos ...

Attempting to send numerous identifiers in an API request

I encountered a problem while working on a function in Angular that involves pulling data from an API. My goal is to enhance a current segment to accommodate multiple IDs, but I face difficulties when attempting to retrieve more than one ID for the API que ...