Exporting an Excel file from JSON with customized formatting and automatic cell adjustment using FileSaver.js

I have successfully implemented functions to export JSON data to Excel using the code below:

  public exportAsExcelFile(json: any[], excelFileName: string) :Promise<Object> {

    const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
    const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
    const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
    return (this.saveAsExcelFile(excelBuffer, excelFileName));

  }

  private saveAsExcelFile(buffer: any, fileName: string):Promise<Object>  {
    const data: Blob = new Blob([buffer], {type: EXCEL_TYPE});
    return await FileSaver.saveAs(data, fileName + '-' + new  Date().toString()+ EXCEL_EXTENSION);
 }

However, I am struggling with formatting the exported Excel file. Specifically, I want to include bold headers and ensure that the cells autofit.

Answer №1

If you're using the js-xlsx library, achieving certain features may require switching to the PRO version, which comes at a high cost.

The community version has its limitations. For enhanced performance, additional styling options, and dedicated support, we recommend upgrading to our PRO version.

Alternatively, you can utilize the ExcelJS library for similar functionalities without the need for expensive upgrades.

 const workbook = new ExcelJS.Workbook();
 workbook.creator = 'Your company name';
 workbook.created = new Date();

 const worksheet = workbook.addWorksheet('Sheet1');

To specify column widths:

 worksheet.columns = [
     { width: 15 },
     { width: 30 },
     { width: 10 }
 ];

You can make headers bold with the following code:

worksheet.getRow(1).font = { bold: true };

Customize cell styles like borders and fonts:

worksheet.getCell('A1').border = {
                    top: ...,
                    left: ...,
                    bottom: ...,
                    right: ...
                };
worksheet.getCell('A1').font = ...;

Lastly, export your file:

import {saveAs} from 'file-saver';
const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';

...
workbook.xlsx.writeBuffer()
             .then((file: any) => {
                const blob = new Blob([file], { type: EXCEL_TYPE });
                saveAs(blob, `fileName.xlsx`);
             });

For more styling options, refer to this link.

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

Methods for maintaining accuracy when updating a user's follower count using Node.js with MongoDB

In my latest project, I am developing a social API system that allows users to follow and unfollow each other. The user model I currently have set up looks like this: sourceId: { type: Schema.Types.ObjectId, ref: "user", required: t ...

Troubleshooting ASP.NET Web API: Resolving Access-Control-Allow-Origin HTTP 500 Error During File Upload

I am facing an issue while trying to upload photos to ASP.NET Web API. I have successfully uploaded files with a size of 17002 or smaller, but encountered errors when attempting to upload files larger than 17345. I have enabled CORS on the Web API and set ...

Tips for incorporating the Sanitize library into Angular 6:

What is the most effective library for sanitization in Angular 6 to enhance security measures? Since injecting dependencies can be tricky, what are some recommended methods for implementing this in an Angular 6 project? ...

Incorporate JavaScript to trigger a click event on a mat-option when the Enter

Situation Within a form field, there is a select dropdown that displays options based on user input in a filter at the top of the list. Desired Outcome The user opens the select dropdown, filters the options by typing, navigates to the desired option us ...

When trying to gather multiple parameters using @Param in a NestJS controller, the retrieved values turn out

Can someone help me understand why I am struggling to retrieve parameters using the @Param() decorators in my NestJS controller? These decorators are defined in both the @Controller() decorator argument and the @Get() argument. I am relatively new to Nest ...

Can Enums be nested in Typescript?

Consider the following enums: export enum Category { FOOD = 'food', DRINK = 'drink' } export enum Type { COLD = 'cold', HOT = 'hot' } Can these be combined into a single enum? For example: export enum Prod ...

Can one create attribute-selector components in a seamless and concealed manner?

In my Angular project, I am utilizing a component library that offers a button component with the selector button[extButton]. However, I have a need for my own custom button components with the selector button[appButton]. Is there a way to apply both comp ...

Ensure that the function parameter only accepts keys that are present in the specified object

I have an object with specific types for its values: type Type = { [key: string]: ValueType } const variable: Type = { key1: valueType, key2: valueType, key3: valueType, } Now, I need a function called func that should only accept keys from v ...

Building React Typescript Components with Froala Editor Plugins

Attempting to integrate a custom plugin into a Froala Editor within my React application using the package react-froala-wysiwyg. Following a tutorial on incorporating a custom popup/plugin found here. Encountering an issue due to TypeScript incompatibility ...

Setting up a reverse proxy for Karma during Angular testing is essential for ensuring that

When developing my application, I rely on a backend web service for API calls. I have successfully configured a reverse proxy for the Angular CLI server using the command ng serve --proxy-config proxy.config.json. Everything works fine in this setup. Howe ...

The pivotal Angular universal service

In my application, I have the need to store global variables that are specific to each user. To achieve this, I created a Service that allows access to these variables from any component. However, I am wondering if there is a way to share this service t ...

What is the best way to divide two ranges that are intersecting?

Seeking a method to divide two overlapping ranges when they intersect. This is my current progress using typescript, type Range = { start: number; end: number; }; function splitOverlap(a: Range, b: Range): Range[][] { let result = []; const inters ...

Can union types be utilized in destructuring with useSelector?

Recently, I have been reevaluating the state structure used in my application and encountered some challenges on how to proceed. Initially, I had set up the following state structure for redux: type State = { loading: boolean loaded: boolean items: ...

Setting the initial state for your ngrx store application is a crucial step in ensuring the

I'm completely new to ngrx and I'm currently exploring how to handle state management with it. In my application, each staff member (agent) is associated with a group of customers. I'm struggling to define the initial state for each agent ob ...

The Firebase.update operation in AngularFire2 encountered an error due to a failure in snapshot

I'm currently working on an Angular2 project and I need to update user profiles in Firebase using AngularFire2. However, I'm encountering an error when trying to update a user profile with the key "nmH5ZmawpQgogoCRVFVfNaBN6xg1". The specific erro ...

How can we effectively divide NGXS state into manageable sections while still allowing them to interact seamlessly with one another?

Background of the inquiry: I am in the process of developing a web assistant for the popular party game Mafia, and my objective is to store each individual game using NGXS. The GitLab repository for this project can be found here. The game includes the f ...

Guide on assigning json array values to multiple accordion forms in Angular 6

Utilizing multiple accordion forms on the same page poses a challenge. When the Add button is clicked, an additional accordion form is added to the page. Upon submitting the second form, a set of JSON data is submitted. The resulting JSON array after three ...

Unable to invoke extension method on parent class in TypeScript

Wondering about classes and extensions in TypeScript? Let's take a look at an example: We have a base class called Report, with another class named Datasheet that extends from Report. An extension has been added to the Report class, and the goal is ...

Tips for deploying an Angular 2+ application on the OpenShift platform

I successfully developed an Angular application on my Windows PC, and now I am facing challenges in deploying it on Red Hat OpenShift. Despite searching for guides online, I have not been able to find helpful resources. If anyone has experience with deploy ...

Navigate smoothly in Angular 4 with Spring Boot without the need for hash codes in the URL routing

Here is the scenario I am facing: I am currently using Spring Boot with Angular 4 I generate a build file using angular-cli and place it under the resource -- static folder. When I run my pom.xml, all the files in the static folder are copied to target ...