How to Import and Export Excel XLSX Using Angular
Tags: angular, webdev, tutorial, devops
Published: 2022-07-29 20:02:00

---
canonical_url: https://developer.mescius.com/blogs/how-to-import-export-excel-xlsx-using-angular
description: Learn how to import and export Excel XLSX files using Angular. See more from SpreadJS today.
---
**What You Will Need**
- Angular 16
- NPM Packages:
    *   [@mescius/spread-sheets-angular](https://www.npmjs.com/package/@mescius/spread-sheets-angular)
    *   [@mescius/spread-sheets](https://www.npmjs.com/package/@mescius/spread-sheets)
    *   [@mescius/spread-sheets-io](https://www.npmjs.com/package/@mescius/spread-sheets-io)
    *   [@mescius/spread-sheets-charts](https://www.npmjs.com/package/@mescius/spread-sheets-charts)
    *   [@mescius/spread-sheets-shapes](https://www.npmjs.com/package/@mescius/spread-sheets-shapes)
    *   [file-saver](https://www.npmjs.com/package/file-saver)
- Visual Studio Code

**Controls Referenced**
- [SpreadJS – Angular Spreadsheet Component](https://developer.mescius.com/spreadjs/angular-spreadsheet-components)
- [Documentation](https://developer.mescius.com/spreadjs/docs/overview) | [Demos](https://developer.mescius.com/spreadjs/demos)

**Tutorial Concept**
Import, modify, and export Excel (.xslx) files in Angular applications.

---
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.

**How to Import and Export Excel Files in Angular Applications**

1.  [<span>Create an Angular Spreadsheet Application</span>](#create)
2.  [<span>Add Excel Import Code</span>](#add-import)
3.  [<span>Programmatically Modify the Imported File</span>](#modify)
4.  [<span>Add Excel Export Code</span>](#add-export)

![Import/Export Excel/XLSX Angular](//cdn.mescius.io/umb/media/cd1e0wwd/01-sjs-angular-importexport.png?rmode=max&width=725&height=462)

Download the [sample application](https://cdn.mescius.io/assets/developer/blogs/spread/20240103-Import-Export-Excel-Angular-SJS/spreadjs-angular-io.zip) to follow along with the blog.

## <a id="create"></a>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 v16**.

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

Install the npm packages for SpreadJS:

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

Open the **angular.json** file and add SpreadJS CSS to the global _styles_ node (as shown below). This applies one of the [<span>built-in themes</span>](https://developer.mescius.com/spreadjs/docs/features/styletheme "https://developer.mescius.com/spreadjs/docs/features/styletheme"), changing the UI of the spreadsheet instance—[refer to our demo for more details](https://developer.mescius.com/spreadjs/demos/features/theme/spread-theme/angular "https://developer.mescius.com/spreadjs/demos/features/theme/spread-theme/angular").

```
    …  
    "projects": {
        "spreadjs-angular-io": {
          …
          "architect": {
            "build": {
             …    
               "styles": [
                  "src/styles.css",
                  "node_modules/@mescius/spread-sheets/styles/gc.spread.sheets.excel2016darkGray.css"
                ],
                …
                }
                …  
              }
              …
            }
            …
          }
        }
        …
     }
```

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

```
    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { AppComponent } from './app.component';
    // Import SpreadJS module
    import { SpreadSheetsModule } from "@mescius/spread-sheets-angular";

    @NgModule({
      declarations: [
        AppComponent
      ],
      // Import SpreadJS module
      imports: [
        BrowserModule, SpreadSheetsModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
```

Open the **app.componet.html** file and delete the placeholder content. Then add SpreadJS’ Angular Template to the application, along with buttons for opening, exporting, and modifying the .xlsx file like so:

```
     <body>
    <div class="left-side"><gc-spread-sheets [hostStyle]="hostStyle" (workbookInitialized)="workbookInit($event)">
    </gc-spread-sheets>
    </div>

    <div class="right-side">
        <p>Open Excel File (.xlsx)</p>
        <input id="selectedFile" type="file" name="files[]" multiple id="jsonFile" accept=".xlsx" (change)="selectedFileChange($event)" />
        <button (click)="open()" id="open">Open Excel</button>

        <p>Add Data</p>
        <button (click)="addCustomer()">Add Customer</button>

        <p>Save Excel File</p>
        <button (click)="save()">Save Excel</button>
    </div>
    </body>
```

Add the following styling to the projects **styles.css** file:

```
    body {
        margin: 0;
        padding: 0;
        display: flex;
        height: 100vh;
    }

    .left-side {
        width: 85%;
        background-color: #f2f2f2;
        padding: 20px;
    }

    .right-side {
        width: 15%;
        background-color: #ddd;
        padding: 20px;
    }
```

Open **app.component.ts** and add the following code add a SpreadJS Angular Component to the application and initialize the workbook.

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

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })

    export class AppComponent {
      title = "SJS-Angular-IO-Excel";
      hostStyle = {
        width: '95%',
        height: '600px'
      };
      private spread;
      columnWidth = 100;

      constructor() {
        this.spread = new GC.Spread.Sheets.Workbook();
      }

      // 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() {

      }
    }
```

Save all the files, and run the Angular app:

```
    npm start
```

You have now created an Angular Spreadsheet app:

![Import/Export Excel/XLSX Angular](//cdn.mescius.io/umb/media/psvncjva/02-setup-sjs-angular-app.png?rmode=max&width=738&height=369)

## <a id="add-import"></a>Add Excel Import Code

SpreadJS has a workbook [**<span>import</span>** method](https://developer.mescius.com/spreadjs/api/v16/classes/GC.Spread.Sheets.Workbook#import "https://developer.mescius.com/spreadjs/api/v16/classes/GC.Spread.Sheets.Workbook#import") 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.componet.ts** file, and add **selectedFile** variable:

```
    export class AppComponent {
      title = "SJS-Angular-IO-Excel";
      hostStyle = {
        width: '95%',
        height: '600px'
      };
      private spread;
      columnWidth = 100;

       // Stores the user-selected file in the selectedFileChange function
      selectedFile: File | any = null;

      constructor() {
        this.spread = new GC.Spread.Sheets.Workbook();
      }
    ...
```

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 [**<span>import</span> **method](https://developer.mescius.com/spreadjs/api/v16/classes/GC.Spread.Sheets.Workbook#import "https://developer.mescius.com/spreadjs/api/v16/classes/GC.Spread.Sheets.Workbook#import"), be sure to specify the [**FileType** as _excel_](https://developer.mescius.com/spreadjs/api/enums/GC.Spread.Sheets.FileType#enumeration-filetype "https://developer.mescius.com/spreadjs/api/enums/GC.Spread.Sheets.FileType#enumeration-filetype").

```
    open() {
        var 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
        };

        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](//cdn.mescius.io/umb/media/sfmdyxrx/03-setup-sjs-angular-app.gif?rmode=max&width=740&height=370)

## <a id="modify"></a>Programmatically Modify the Imported 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:

```
    export class AppComponent {
      title = "SJS-Angular-IO-Excel";
      hostStyle = {
        width: '95%',
        height: '600px'
      };
      private spread;
      private currentCustomerIndex = 0;
      columnWidth = 100;

       // Stores the user-selected file in the selectedFileChange function
      selectedFile: File | any = null;

      constructor() {
        this.spread = new GC.Spread.Sheets.Workbook();
      }
    ...
```

Update the **addCustomer** function to [<span>add a new row</span>](https://developer.mescius.com/spreadjs/api/v17/classes/GC.Spread.Sheets.Worksheet#addrows "https://developer.mescius.com/spreadjs/api/v17/classes/GC.Spread.Sheets.Worksheet#addrows"), [copy the styles of the previous row](https://developer.mescius.com/spreadjs/api/v17/enums/GC.Spread.Sheets.CopyToOptions#enumeration-copytooptions "https://developer.mescius.com/spreadjs/api/v17/enums/GC.Spread.Sheets.CopyToOptions#enumeration-copytooptions"), and [apply the new customer data within the customerDataArrays](https://developer.mescius.com/spreadjs/api/classes/GC.Spread.Sheets.Worksheet#setarray "https://developer.mescius.com/spreadjs/api/classes/GC.Spread.Sheets.Worksheet#setarray").

```
    // Modify data imported
      addCustomer() {
        // create new row and copy styles
        var newRowIndex = 34;
        var 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
        var 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
        var 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](//cdn.mescius.io/umb/media/z51nsysp/04-modify-data-sjs-angular-app.gif?rmode=max&width=754&height=377)

## <a id="add-export"></a>Add Excel Export Code

With the [**<span>export</span>**](https://developer.mescius.com/spreadjs/api/v16/classes/GC.Spread.Sheets.Workbook#export "https://developer.mescius.com/spreadjs/api/v16/classes/GC.Spread.Sheets.Workbook#export") [method](https://developer.mescius.com/spreadjs/api/v17/classes/GC.Spread.Sheets.Workbook#export "https://developer.mescius.com/spreadjs/api/v17/classes/GC.Spread.Sheets.Workbook#export") included with SpreadJS and the [file-saver npm package](https://www.npmjs.com/package/file-saver "https://www.npmjs.com/package/file-saver"), Angular app developers can effortlessly export a spreadsheet state as an Excel file. First, install the file-saver npm package.

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

In the **angular.json** file, add the **file-saver** component to the global _scripts_ node.

```
    …  
    "projects": {
        "spreadjs-angular-io": {
          …
          "architect": {
            "build": {
             …    
               "styles": [
                  "src/styles.css",
                  "node_modules/@mescius/spread-sheets/styles/gc.spread.sheets.excel2016darkGray.css"
                ],
                "scripts": ["node_modules/file-saver/dist/FileSaver.js"]
                …
                }
                …  
              }
              …
            }
            …
          }
        }
        …
     }
```

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

```
    import { Component } from '@angular/core';
    import '@mescius/spread-sheets-angular';
    import * as GC from "@mescius/spread-sheets";
    import '@mescius/spread-sheets-io';
    import '@mescius/spread-sheets-charts';
    import '@mescius/spread-sheets-shapes';
    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() {
        var fileName = 'Excel_Export.xlsx'
        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](//cdn.mescius.io/umb/media/ejtejfjb/05-save-excel-file.gif?rmode=max&width=752&height=376)

Don’t forget to download this blog's [sample application](https://cdn.mescius.io/assets/developer/blogs/spread/20240103-Import-Export-Excel-Angular-SJS/spreadjs-angular-io.zip) 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 [**<span>SpreadJS</span>**](https://developer.mescius.com/spreadjs/angular-spreadsheet-components "https://developer.mescius.com/spreadjs/angular-spreadsheet-components"), the Angular spreadsheet component. Review the [documentation](https://developer.mescius.com/spreadjs/docs/overview "https://developer.mescius.com/spreadjs/docs/overview") to see some of the many available features, and check out our [online demos](https://developer.mescius.com/spreadjs/demos "https://developer.mescius.com/spreadjs/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.

To learn more about SpreadJS and the new features added with the v17 release, check out our [<span>release blog</span>](https://developer.mescius.com/blogs/spreadjs-v17-is-released "https://developer.mescius.com/blogs/spreadjs-v17-is-released") and this video:

{% embed https://youtu.be/jACaSv6JVAc %}