Skip to main content Skip to footer

How to Import and Export Excel XLSX Using Angular

  • 0 Comments
Quick Start Guide
Tutorial Concept Learn how to import, modify, and export Excel (.xlsx) files in Angular applications.
What You Will Need

Angular 20
NPM Packages:

Visual Studio Code

Controls Referenced

SpreadJS – Angular Spreadsheet Component

Documentation | Demos

This article demonstrates how you can import and export Excel spreadsheets in an Angular environment using an Angular spreadsheet component; in this example, that will be SpreadJS. SpreadJS offers Angular developers a familiar Excel-like spreadsheet UI and import/export capabilities without any dependencies on Microsoft Excel.

Ready to Try It Out? Download SpreadJS Today!

How to Import and Export Excel (.XLSX) Files in Angular Applications

  1. Create an Angular Spreadsheet Application
  2. Add Excel Import Code - Import Method
  3. Add Data to the Imported Excel File
  4. Add Excel Export Code - Export Method

Try Out an Import and Export Sample

You can also download the full sample to run locally.


Create an Angular Spreadsheet Application

Install the @angular/cli package.

npm i -g @angular/cli

Create a new Angular project. In this example, we will be using Angular v20.

ng new spreadjs-angular-io
cd spreadjs-angular-io

Install the npm packages for SpreadJS:

npm install @mescius/spread-sheets
npm install @mescius/spread-sheets-angular
npm install @mescius/spread-sheets-io
npm install @mescius/spread-sheets-charts

Next, open the app.ts file and add the necessary imports for the SpreadJS module, as noted below.

import { Component } from '@angular/core';
import { SpreadSheetsModule } from "@mescius/spread-sheets-angular";
import * as GC from "@mescius/spread-sheets";
import '@mescius/spread-sheets-io';
import '@mescius/spread-sheets-charts';

@Component({
  selector: 'app-root',
  imports: [SpreadSheetsModule],
  template: `  
    Welcome to Angular!
  `,
  styles: [],
})
export class App {
  protected title = 'spreadjs-angular-io';

}

In the app.ts file delete the template's placeholder contents (or in the app.html file if you are using a templateUrl). Then add SpreadJS’ Angular Template to the application, along with buttons for opening, exporting, and modifying the .xlsx file like so:

@Component({
  selector: 'app-root',
  imports: [SpreadSheetsModule],
  template: `
  <div class="container">
    <div class="spread-panel">
      <gc-spread-sheets [hostStyle]="hostStyle" (workbookInitialized)="workbookInit($event)">
      </gc-spread-sheets>
    </div>
    <div class="side-panel">
        <label for="selectedFile">Open Excel .xlsx File:</label>
        <input id="selectedFile" type="file" accept=".xlsx" (change)="selectedFileChange($event)" />
        <button (click)="open()" id="open">Import</button>
        <br/>
        <label>Add Data</label><br/>
        <button (click)="addCustomer()">Add Customer</button>
        <br/>
        <label>Export Excel file:</label><br/>
        <button (click)="save()">Export File</button>
    </div>
  </div>
  `,
  styles: [],
})

In the app.ts file, add the following code to the App class to add the Angular spreadsheet component to the application and initialize the workbook. We also have a few placeholder functions that we will fill out later.

export class App {
  protected title = 'spreadjs-angular-io';

   hostStyle = {
    width: '100%',
    height: '600px'
  };
  
  spread: GC.Spread.Sheets.Workbook | any = null;
  columnWidth = 100;

  constructor() {
  }
  
  // Initialize SpreadJS
  workbookInit($event: any) {
    this.spread = $event.spread;
  }
  // Get the selected Excel file
  selectedFileChange(e: any) {
  }
  // Imported the Excel file into SpreadJS
  open() {
  }
  // Modify data imported
  addCustomer() {
  }
  // Save the instance as an Excel File
  save() {
  }
}

Open the styles.css file and import the SpreadJS stylesheet (as shown below). This applies one of the built-in themes, changing the UI of the spreadsheet instance—refer to our demo for more details. We will also add some styles for the layout of the SpreadJS panel and side panel.

@import '@mescius/spread-sheets/styles/gc.spread.sheets.excel2016darkGray.css';

body {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI Light', Roboto,
    Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif;
}
.container {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  height: 100%;
}
.spread-panel {
  flex: 1 1 auto;
}
.side-panel {
  width: 200px;
  padding: 1rem;    
  background-color: #f2f2f2;
}
.side-panel input {
  width: 100%;
  min-width: 100px;
}

Save all the files, and run the Angular app:

npm start

You have now created an Angular Spreadsheet app:

Import/Export Excel/XLSX Angular Application


Add Excel Import Code to an Angular App

SpreadJS has a workbook import method that imports the object state from Excel. Before we can invoke this method, we must get the user-selected .xlsx file. To do this, we will go to the app.ts file, and add selectedFile variable:

export class App {
  protected title = 'spreadjs-angular-io';

   hostStyle = {
    width: '100%',
    height: '600px'
  };
  spread: GC.Spread.Sheets.Workbook | any = null;
  columnWidth = 100;
   // Stores the user-selected file in the selectedFileChange function
  selectedFile: File | any = null;
  constructor() {
    
  }
...

In the selectedFileChange() function store the selected file object in the selectedFile variable :

// Get the selected Excel file
  selectedFileChange(e: any) {
      this.selectedFile = e.target.files[0];
}

Now, in the open() function, with the selectedFile, invoke the SpreadJS import method, be sure to specify the FileType as excel.

open() {
    let file = this.selectedFile;
        if (!file) {
            return;
        }
    // Specify the file type to ensure proper import
    const options: GC.Spread.Sheets.ImportOptions = {
      fileType: GC.Spread.Sheets.FileType.excel
    };

    if(this.spread){
      this.spread.import(file, () => {
        console.log('Import successful');
      }, (e: any) => {
        console.error('Error during import:', e);
      }, options);
    }
}

With these steps, you've successfully add Excel import functionality to the Angular spreadsheet application.

Import/Export Excel/XLSX Angular


Add Data to the Import Excel File

After successfully importing an Excel file into SpreadJS, you may find it necessary to programmatically modify the data within the spreadsheet. This section introduces the function addCustomer(), which adds new customer data to the imported .xlsx file data when a button is clicked. First, we need to create a currentCustomerIndex variable, this will be used as a counter related to the sample data:

 protected title = 'spreadjs-angular-io';

   hostStyle = {
    width: '100%',
    height: '600px'
  };
  spread: GC.Spread.Sheets.Workbook | any = null;
  protected currentCustomerIndex = 0;
  columnWidth = 100;
   
   // Stores the user-selected file in the selectedFileChange function
  selectedFile: File | any = null;

  constructor() {
    
  }
...

Update the addCustomer() function to add a new row, copy the styles of the previous row, and apply the new customer data within the customerDataArrays.

// Modify data imported
  addCustomer() {
    // create new row and copy styles
    let newRowIndex = 34;
    
    if(this.spread){
      let sheet = this.spread.getActiveSheet();
      sheet.addRows(newRowIndex, 1);  
      sheet.copyTo(32, 1, newRowIndex, 1, 1, 11, GC.Spread.Sheets.CopyToOptions.style);  
      // Define sample customer data
      let customerDataArrays = [
          ["Jessica Moth", 5000, 2000, 3000, 1300, 999, 100],
          ["John Doe", 6000, 2500, 3500, 1400, 1000, 20],
          ["Alice Smith", 7000, 3000, 4000, 1500, 1100, 0]
      ];
      // Get the current customer data array
      let currentCustomerData = customerDataArrays[this.currentCustomerIndex];
      // Add new data to the new row
      sheet.setArray(newRowIndex, 5, [currentCustomerData]);
      newRowIndex++;
      // Increment the index for the next button click
      this.currentCustomerIndex = (this.currentCustomerIndex + 1) % customerDataArrays.length;
    }
}

Notice, that when the button is clicked, new customer data is added to the statement, and the formulas within the worksheet update accordingly.

Modify Data Angular


Add Excel Export Code to an Angular App

With the export method included with SpreadJS and the file-saver npm package, Angular app developers can effortlessly export a spreadsheet state as an Excel file. First, install the file-saver npm package.

npm install file-saver
npm i --save-dev @types/file-saver

Import the file-saver package to the app.ts file.

import { Component } from '@angular/core';
import { SpreadSheetsModule } from "@mescius/spread-sheets-angular";
import * as GC from "@mescius/spread-sheets";
import '@mescius/spread-sheets-io';
import '@mescius/spread-sheets-charts';
import { saveAs } from 'file-saver';
...

Next, update the save() function by first specifying the exported XLSX file name; we used “Excel_Export.xlsx”, then invoke the SpreadJS export method, which exports the current spreadsheet state into a Blob. Within the export method, invoke the file-saver's saveAs method to save the exported spreadsheet Blob as an actual Excel file on the client side.

// Save the instance as an Excel File
  save() {
    let fileName = 'Excel_Export.xlsx'
    if(this.spread){
      this.spread.export(function (blob:any) {
        // save blob to a file
        saveAs(blob, fileName);
      }, function (e:any) {
          console.log(e);
      }, {
          fileType: GC.Spread.Sheets.FileType.excel
      });
    }
  }

With these steps, you've successfully added Excel export functionality to the Angular spreadsheet application.

Save Angular Excel File

Don’t forget to download this blog's sample application to try importing/exporting your own Excel files.


Learn More About this Angular Spreadsheet Component

This article only scratches the surface of the full capabilities of SpreadJS, the Angular spreadsheet component. Review the documentation to see some of the many available features, and check out our online demos to see the features in action and interact with the sample code. Integrating a spreadsheet component into your applications allows you to customize your users' experience and provide them with familiar spreadsheet functionality without referring them to an external program.

Ready to Try It Out? Download SpreadJS Today!

To learn more about SpreadJS and the new latest release features, check out our release pages releases and this video:

In another article series, we demonstrate how to import/export Excel (.xlsx) spreadsheets in other frameworks: