As a developer, you are open to facing new challenges daily in different projects you may be working on. Web applications sometimes have to perform some extra tasks to achieve different goals depending on business or technical requirements.

You might need to collect data from an API and process it in a different format such as PDF, XML, DOCX, or XLSX.

In this guide, you will learn how to transform JSON data received from an API response into a well-organized Excel spreadsheet in your Angular application.

What Is the XLSX Library?

The Xlsx library is an effective resource for Angular developers who want to transform JSON data from an API response into a neat Excel spreadsheet. Through the use of this module, developers may quickly download and modify JSON data.

You can use the Xlsx library to create reports for your team or to present data in new ways. If you want a quick and easy way to manage your data in JavaScript applications, this is a good option.

How to Configure the XLSX Library With an Angular Application

Before getting started with the Xlsx library in your Angular application, it is important to have a Node.js and Angular development environment set up on your machine. With Node.js installed, Angular is easy to set up by running npm install -g @angular/cli in a terminal.

Create a new Angular project by running ng new [your-angular-app-name] in the terminal. Then navigate into the project directory as seen below:

terminal output for angular create new project

You may also start a local development server by running ng serve --o, which enables you to view your Angular application and changes made to it live in the browser.

Having set up an Angular application, installing the Xlsx Library is a simple process that you can complete simply by running npm install xlsx --save. This command will install the dependencies needed to use the Xlsx library.

How to Convert JSON Data to XLSX Format in Angular

With the Angular CLI, you can generate a new service by running the ng generate service [service name] command in the terminal. For example, in this case, you can generate the Excel service you need using ng generate service ExcelService.

This generate command will create the service file: ExcelService.service.ts, in the src/app directory of the project. The file looks like this by default:

        import { Injectable } from '@angular/core'; 

@Injectable({ providedIn: 'root' })

export class ExcelServiceService {
  constructor() { }
}

This ExcelService file will handle the functionality to export data to Excel format. Update the ExcelService.service.ts file to look like the code below:

        import { Injectable } from '@angular/core'; 
import * as XLSX from 'xlsx';

const EXCEL_EXTENSION = '.xlsx'; // excel file extension

@Injectable({ providedIn: 'root' })

export class ExcelServiceService {
  constructor () { }

  public exportToExcel (element: any, fileName: string): void {
    // generate workbook and add the worksheet
    const ws: XLSX.WorkSheet = XLSX.utils.json_to_sheet(element);
    const workbook: XLSX.WorkBook = XLSX.utils.book_new();

    // save to file
    XLSX.utils.book_append_sheet(workbook, ws, 'Sheet1');
    XLSX.writeFile(workbook, ${fileName}${EXCEL_EXTENSION});
  }
}

In the above code, you import the Xlsx library and create a constant variable, EXCEL_EXTENSION to store the Excel file extension.

The exportToExcel method accepts two parameters: element and fileName. The element parameter represents the data to export to the Excel file, while the fileName parameter is the name of the Excel file.

To export the data to the Excel file, create a worksheet using the json_to_sheet method of the Xlsx library. Also create a workbook using the library’s book_new method.

Then, add the worksheet to the workbook with the book_append_sheet method, and save the to a file using writeFile.

Earlier on, you created an Excel service to facilitate the process of downloading and converting JSON data to an Excel sheet. To use this service, you need to create the relevant Angular component and import the service file into it.

        import { ExcelService } from './excel.service';

Next, you have to inject it into the constructor of the component like this:

        constructor(private excelService: ExcelService) { 
  ....
}

Then you may go ahead to implement the function (exportExcel) where you will use the exportToExcel method to export JSON to Excel. The code below demonstrates how to do this.

        exportExcel(): void { 
  const fileToExport = this.apiJsonResponseData.map((items:any) => {
    return {
     "User Id": items?.userId,
     "Id": items?.id,
     "Title": items?.title,
     "Body": items?.body
   }
  });

  this.excelService.exportToExcel(
   fileToExport,
   'yourExcelFile-' + new Date().getTime() + '.xlsx'
 );
}

In the code above, you have defined the exportExcel method to call the exportToExcel method of the ExcelService. The new variable, fileToExport, stores the data to export. The apiJsonResponseData array contains the JSON data obtained from the API response.

Subsequently, the exportToExcel method of the excelService takes the fileToExport and your preferred filename. Notice how you can append the current timestamp to the filename to ensure it’s unique. This method will convert the JSON data and export it to an XLSX file which you can then preview in Excel.

This function is now available to use in any part of your Angular application, and you may easily add it as an event handler for a click event or use it in any other suitable way based on your requirements.

You can see an example use of this functionality in the image below. JSON data from an external API renders on the page, with a button to Export Data to Excel:

data on web page with button to export to excel

When you click the Export Data to Excel button, your browser will download the Excel file. When you open the XLSX file, the output spreadsheet file looks like this:

Excel output aftter converting from JSON

The Xlsx library can do a lot more than convert JSON to Excel format. It offers a robust library and supports various file formats that you might encounter in business. Check out the Xlsx library's documentation on npm to find out more about it.

Converting Data From JSON to Excel Spreadsheets in Angular

You can use the Xlsx library to easily manipulate Excel spreadsheets in your web application. The steps you’ve carried out here let you transform JSON data from an API into a well-organized Excel spreadsheet. You can also convert Excel data back to JSON using other functions in the library.

A good way to practice using this library is to build an application that generates weekly or monthly reports from an API and organizes them as Excel data.