Create Excel File In Angular

Introduction:

For data organizing and financial analysis, Excel is commonly used. All sizes and types of organizations use it in their daily operations.

This post demonstrates how to create an excel file in Angular. In order to create the excel file, we start over entirely by installing Angular.

Prerequisites:

Before starting this instruction, ensure that you have npm installed on your computer. We will use npm to find and install the required dependencies for our application. Also required are code editors. The entire course makes use of Visual Studio Code.

Get Started:

Step 1: Set up your project.

After selecting the folder where you wish to create an Angular project, type the following command into a terminal or command window.

ng new excel-file

Once the installation is complete, open the folder in your code editor. Run ng serve -o to launch the development server. You can view the default React application by opening your browser and browsing to http://localhost:4200

Step 2: Install xlsx package.

We must first install the xlsx package. So open your terminal, and make sure you are in the application’s master folder.

npm install xlsx --save

Step 3: Add bootstrap for styling.

npm install --save bootstrap

Then import bootstrap CSS in your styles.css file.

@import '~bootstrap/dist/css/bootstrap.min.css';

Step 5: Open app.component.ts file and import the xlsx library.

import * as XLSX from 'xlsx';

Add some sample data and generateExcelFile() method.

export class AppComponent {

  sampleData: any = [
    {
      id: 1,
      name: "test1"
    },
    {
      id: 2,
      name: "test2"
    },
    {
      id: 3,
      name: "test3"
    },
  ]

  generateExcelFile() {
    const ws: XLSX.WorkSheet = XLSX.utils.json_to_sheet(this.sampleData);  
    const wb: XLSX.WorkBook = XLSX.utils.book_new();  
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');  
    XLSX.writeFile(wb, 'sample.xlsx');  
  }  

}

Step 6: Add the following HTML for invoking generateExcelFile() method.

<div class="mt-5 text-center">
  <button class="btn btn-success" (click)="generateExcelFile()">Generate</button>
</div>

Finally, save your code and check the output on the browser.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories