How to Import and Export Excel XLSX Using Angular

Chelsea Devereaux - Jul 29 '22 - - Dev Community

What You Will Need

Controls Referenced

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. Create an Angular Spreadsheet Application
  2. Add Excel Import Code
  3. Programmatically Modify the Imported File
  4. Add Excel Export Code

Import/Export Excel/XLSX Angular

Download the sample application to follow along with the blog.

Create an Angular Spreadsheet Application

Install the @angular/cli package.

    npm i -g @angular/cli
Enter fullscreen mode Exit fullscreen mode

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

    ng new spreadjs-angular-io
    cd spreadjs-angular-io
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Open the angular.json file and add SpreadJS CSS to the global styles node (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.

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

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 { }
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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;
    }
Enter fullscreen mode Exit fullscreen mode

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

      }
    }
Enter fullscreen mode Exit fullscreen mode

Save all the files, and run the Angular app:

    npm start
Enter fullscreen mode Exit fullscreen mode

You have now created an Angular Spreadsheet app:

Import/Export Excel/XLSX Angular

Add Excel Import Code

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.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();
      }
    ...
Enter fullscreen mode Exit fullscreen mode

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];
    }
Enter fullscreen mode Exit fullscreen mode

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

    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);
      }
Enter fullscreen mode Exit fullscreen mode

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

Import/Export Excel/XLSX Angular

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();
      }
    ...
Enter fullscreen mode Exit fullscreen mode

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
        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;
      }
Enter fullscreen mode Exit fullscreen mode

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

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 --save
    npm i --save-dev @types/file-saver
Enter fullscreen mode Exit fullscreen mode

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"]
                …
                }
                …  
              }
              …
            }
            …
          }
        }
        …
     }
Enter fullscreen mode Exit fullscreen mode

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';
    ...
Enter fullscreen mode Exit fullscreen mode

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
        });
      }
Enter fullscreen mode Exit fullscreen mode

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.

To learn more about SpreadJS and the new features added with the v17 release, check out our release blog and this video:

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .