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

The command '.' is unable to be executed as an internal or external command, executable program, or batch file when using npm start -- -e=stag -c=it

After executing the command shown below npm start -- -e=stag -c=it An error is generated: ./scripts/start.js -e=stag -c=it '.' is not recognized as an internal or external command, operable program or batch file. What can be done to resolve th ...

Completes a form on a separate website which then populates information onto a different website

Creating a website that allows users to login and view various complaint forms from government websites or other sources. When a user clicks on a link to file a complaint, they will be redirected to the respective page. However, I am looking for a way to ...

unable to update the table due to issues with the knockout observableArray

My goal is to collect values from form fields and store them as an object in an observableArray. I want to display these objects in a table so that every time I hit the 'add' button, the table should be updated. However, I am facing issues with t ...

There seems to be an issue with the hidden field value not being properly set within the

I created a function called getConvertionValue. Inside this function, I make an ajax call to the getCurrencyConvertion function in the controller. function getConvertionValue(from, to) { if (from != to) { $.ajax({ url: base_url + 'admin/o ...

Storing user input in a MongoDB database using Angular and Node.js

I recently embarked on a journey to learn AngularJS, and decided to create a simple blog application to dive into MongoDB and $http requests. However, I'm facing challenges with using my Angular service to send the user-filled form data from $scope t ...

Tips for customizing the border of an outlined TextField in MUI

Below is the current configuration of a TextField component: const styles = { resize: { fontSize: '50px', } } const textField = (props) => { const { classes } = props; return ( <TextField valu ...

Leverage the power of Pandas to easily parse through complex nested JSON data with either the

My JSON object has a complex structure, here's a snippet: import pandas as pd json_data_raw = [{"indicator_value":{"195606": {"2010":{"AFG": 0.29, ...

Updating JSON data post XMLHttpRequest call

Currently experiencing a puzzling moment. I'm attempting to insert more information into my object after retrieving it from an external source (just for testing purposes, I intend to add random values). Without further ado: As an example, here is w ...

Achieving synchronous function execution with a single click in React

In my current project, I am utilizing ReactJs and Redux. I have encountered a scenario where I need to trigger two functions sequentially with just one click on the mainfunc(). The second function should only execute after the first function has complete ...

Struggle with Transmitting Information in Ionic 2

I have been working on an Ionic project that involves a JSON file with preloaded data. The initial page displays a list from which a user can select an item to view its content. However, I am encountering a "Response with status: 404 Not Found for URL" err ...

Encountering a critical issue with Angular 12: FATAL ERROR - The mark-compacts are not working effectively near the heap limit, leading to an allocation failure due

After upgrading my Angular application from version 8 to 12, I encountered an issue. Previously, when I ran ng serve, the application would start the server without any errors. However, after updating to v12, I started receiving an error when I attempted t ...

obtain a Javascript variable within a Jade template by using inline code

script. var hide_section = 'block'; .title(style='display:#{hide_section}') I received an undefined value, any thoughts on why? Could it be because #{hide_section} is trying to access a variable from the back-end, such as the cont ...

JavaScript: Use onclick events to change the class of a div on multiple divs

I have a jQuery script that allows for toggling of the parent class when #icon is clicked. Additionally, when the body is clicked, it reverts back to the original class. Now, I'm looking to achieve the same behavior when clicking on #item5 or #item4 a ...

Display a dropdown menu when clicking on a close button in a single element using Vanilla JavaScript

I'm currently in the process of learning Javascript and trying to grasp the concept of events and selectors. My aim is to have a close button that, when clicked, triggers a specific dropdown related to the card it's attached to. I plan to achie ...

A method for reversing specific characters within lengthy strings

I'm currently tackling a coding problem: For a given string s and an integer k, the task is to reverse the first k characters for every 2k characters starting from the beginning of the string. If there are less than k characters remaining, reverse al ...

Having trouble extracting the date modified from a JSON file

I am able to retrieve section name, URL, web title, and headline from parsing JSON data with this code snippet. However, I seem to be encountering an issue where I cannot extract the last modified date. Here is the JSON structure: { "response":{ ...

The API response indicating success is simply denoted as "Success: True", without any accompanying data

I've set up my application on an express server with a proxy to communicate with the API server. Here's a snippet of my code: HTML: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> ...

What is the best way to restrict the input options for a String field within a TextField component in Material-UI?

When working with Material-UI, how can we set a maximum length restriction for a text field? Below you will find an example of the TextField component: <TextField id="name" label="Name" type="string" //maxLengt ...

Vue.js - computed property not rendering in repeated list

It seems like the issue lies in the timing rather than being related to asynchronous operations. I'm currently iterating through an object and displaying a list of items. One of the values requires calculation using a method. While the direct values ...

Creating Javascript objects using provided JSON data

Good day! I am looking for assistance in understanding how to create objects from JSON data that has been provided: { "type":"FeatureCollection", "features":[ { "type":"Feature", ...