Generating a .xls file from JSON data and saving it for download

I'm trying to encode a JSON object to XLSX and download it using the following code:

this.data = {
   foo: "xyz"
}
let json2xls = require('json2xls');
var data = json2xls(this.data);

let blob = new Blob([data], { type: "binary" });
let a = angular.element("a");
a.attr("href", this.$window.URL.createObjectURL(blob));
a.attr("download", "myfile.xlsx");
a[0].click();

Although the file is being created and downloaded, Excel cannot open it. I have verified that a different method works by sending this.data to the server, saving it with fs.writeFile(), and then downloading the file.

var data = json2xls(this.data);

Is there a way to successfully convert from JSON to XLS in a browser environment?

Answer №1

To achieve this, you can implement it on the server side:

  • Start by installing exceljs package.

npm install -s exceljs

  • After installation, proceed to generate the file using the following steps:

import Excel from 'exceljs';

WebApp.connectHandlers.use('/download-link', function(req, res, next) {
  // Define parameters for the xls generation process using request url...
  const params = req.url.split('/');
  // ... e.g. /download-link/user-id
  // Here, params[0] will be 'download-link'
  const user = Meteor.users.findOne(params[1]);

  const workbook = new Excel.stream.xlsx.WorkbookWriter({});
  workbook.created = new Date();
  workbook.modified = new Date();
  const sheet = workbook.addWorksheet('Your sheet name');

  res.writeHead(200, {
    'Content-Disposition': `attachment;filename=${filename}`,
    'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  });
  workbook.stream.pipe(res);

  const headers: [
        { header: 'Column 1', key: 'col1', width: 20 },
        { header: 'Column 2', key: 'col2', width: 15 },
  ];
  sheet.columns = headers;

  // Use sheet.addRow(rowData) to add each row in your sheet.

  workbook.commit();
});

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

Processing file to retrieve information (JavaScript)

As someone who is new to the world of JavaScript and website development, please forgive me if this question seems a bit basic. The concept is to have a popup message appear on every page with some information. The issue arises when wanting to change this ...

Rules for validating string and numeric combinations in Vuetify are essential for ensuring accurate

Looking for guidance on implementing Vuetify validation to enforce rules (using :rules tag on a v-text-field) in the format of AB-12345678 (starting with two letters followed by a hyphen and then an 8-digit number). I'm having difficulty achieving thi ...

Interactive Checkbox Generated in Jquery UI Accordion Header

I need help creating an accordion with checkboxes in the headers dynamically populated from a database. I have tried using the click() function to prevent the accordion from activating when checking the checkbox, but since the accordion is generated dynami ...

How can you efficiently load images as you scroll without encountering duplicates?

After researching various forums and tutorials, I have learned how to dynamically load data using AJAX calls to a database via PHP files for asynchronous loading. To display images in a random order with a limit of 12, I can use a select statement like SE ...

Tips on implementing two ng-repeat directives within a specific element

Inside a JSON file, there is an array that needs to be iterated within <td> tags. The functionality entails creating a table based on user input, which includes the number of rows, input columns, and output columns provided by the user. Three arrays ...

Merge jQuery with the jetpack infinite scroll feature

Utilizing the jQuery code below for an accordion effect on all my WordPress posts on the front end. (function($) { function initAccordion() { var $ele = $('.entry-content').hide(); $(".entry-header").unbind('click&apos ...

Opening a new tab on any webpage with C# Selenium

Is there a foolproof way to open a new tab when using Selenium? Trying to use an action method has proven unsuccessful Actions a = new Actions(driver); a.KeyDown(OpenQA.Selenium.Keys.LeftControl); a.SendKeys("t"); a.KeyUp(OpenQA.Selenium.Keys.L ...

Use the map function to pass onClick to every individual image

I need help passing an onClick function to each thumbnail image created with the map function. The goal is for the main image to change to the clicked thumbnail when a user selects it. Currently, it seems like the onClick function is being triggered witho ...

Tips for showcasing live data in Material-UI's table component

My challenge lies in displaying tabular data fetched from an API in a Material-UI Table. Specifically, I aim to exhibit the fields id and name stored within groups. How can I achieve this result? Beneath is my current code snippet which runs without error ...

Which type of element does Youtube utilize for the videos on its own domain - <iframe> or <video>?

Do they have a different method for incorporating their videos? My goal is to utilize the playbackRate property on a non-embedded YouTube video for a Chrome extension. ...

The performance of json.JSONDecoder().decode() may not be optimal

Despite the simplicity of the code, it is not functioning properly. The issue at hand remains a mystery to me. import json json_data = '{text: \"tl4ZCTPzQD0k|rEuPwudrAfgBD3nxFIsSbb4qMoYWA=\", key: \"MPm0ZIlk9|ADco64gjkJz2NwLm6SWHvW&bs ...

It seems that there is an issue with accessing the root directory while utilizing the yo

I'm currently working on setting up the Yeoman 1.0 beta's angular scaffolding and have been following these steps in my workflow: npm install generator-angular generator-testacular # installing generators yo angular # creati ...

Creating JavaScript object fields with default values in an AngularJS model: A Step-by-Step Guide

As I work on developing the model layer for my AngularJS application, I came across some valuable advice on using functions to create objects. This source emphasizes the use of functions like: function User(firstName, lastName, role, organisation) { // ...

Access control and permissions in Angular's UI router

I am struggling to figure out how to implement permissions and access control in our Angular app. Currently, our setup looks like this: app.config(['$stateProvider', function ($stateProvider) { $stateProvider .state('default', { ...

I am facing an issue where childnodes return as undefined after a clone operation, making it impossible for me to assign their attributes as needed,

There seems to be an issue with changing the attributes of my child nodes as they are returning as undefined. It's possible that the problem arises when the nodes are placed in a list. Upon testing, it was discovered that placing the nodes in a list c ...

Ensure that the JavaScript file is fully loaded and that the JavaScript function has been properly initiated prior to executing any additional

Having an issue with a tracking code not working properly as it is called before a required JS script and function is loaded. The situation is as follows: Upon successful form submission (CF7 on WordPress), the following function is immediately called. ...

Unable to render images in Angular client due to issues with accessing upload path in Express Node.js backend

I've been struggling with the issue of displaying images on the Angular client for a while now, despite going through numerous similar questions. The files are successfully uploaded to the upload folder and their details are stored in the MongoDB data ...

What causes meteor to freeze when utilizing WebApp and sending npm package to serve personalized files?

I have developed a customized upload and serve system for handling media files in a meteor application. The Issue After approximately 800 to 4000 files (this number varies depending on the system) are served to a browser, the entire application freezes. ...

How can you alter a property within an array of records retrieved from a Mongoose query?

const images = await tbl .find({ creator_id: req.user._id, }) .select({ creator_id: 0, }) .exec() .then((images) => images.forEach((image) => { image.file_name = process.env.IMAGE_ ...

Reproducing a table row

Here is the table structure I am working with: <table id="customFields" class="table table-bordered table-hover additionalMargin alignment"> <thead> <tr> <th colspan="2"></th> <th>Some Title</ ...