How to Add an Angular Excel XLSX Viewer to Your Web Application
Tags: webdev, devops, javascript, tutorial
Published: 2023-06-21 11:39:51

---
canonical_url: https://developer.mescius.com/blogs/how-to-add-an-angular-excel-xlsx-viewer-to-your-web-application
description: Learn how to add an Angular Excel XLSX viewer to your web application. See more from SpreadJS today.
---
As a client-side control, SpreadJS, our JavaScript spreadsheet, can be used with different frameworks, including Angular. This blog will use SpreadJS and Angular 15 to show you how to add an XLSX Viewer to your applications and allow your users to view Excel files easily.

![Angular Excel XLSX Viewer](https://files.grapecity.com/gc-website-media/pyybdkhr/02-angular.png?width=500&height=232.63254113345522)

Download [the sample](/{localLink:umb://media/138ae8b36e84476c8a8981a9be37340e} "Spreadsheet_SJS_05/26/23") to follow along.

## Installing Angular

Before working with Angular, we need to make sure it is installed. To do this, we can install the Angular CLI with a command prompt:

```
    npm install -g @angular/cli
```

This will install the latest Angular globally.

## Creating a New Project

Now, we can create a new project using the terminal as well:

```
    ng new spread-sheets-angular-cli
    cd spread-sheets-angular-cli
```

In that project, we can use NPM to add the required SpreadJS libraries in the project:

```
    npm install @grapecity/spread-sheets
    npm install @grapecity/spread-sheets-angular
```

We also need to add the styles to the angular.json file:

```
    {
      ...
      "projects":{
        "spread-sheets-angular-cli":{
          ...
          "architect":{
            ...
            "build":{
              ...
              options:{
                ...
                "styles": [
                  "node_modules/@grapecity/spread-sheets/styles/gc.spread.sheets.excel2016darkGray.css"
                ],
                ...
              }
              ...
            }
            ...
          }
          ...
        }
      }
      ...
    }
```

We are now ready to add code to add SpreadJS into this application.

## Add SpreadJS Code

The first SpreadJS code we need to add is in the **src>app>app.module.ts** file:

```
    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { AppComponent } from './app.component';
    import { SpreadSheetsModule } from "@grapecity/spread-sheets-angular";
    @NgModule({
    declarations: [AppComponent],
    imports: [BrowserModule,SpreadSheetsModule],
    providers: [],
    bootstrap: [AppComponent]
    })
    export class AppModule { }
```

Now that we have some background code for the App module, we can start working on the component. The first thing we can change is the **src>app>app.component.html** file (there is some code in here for functions that don’t exist yet, we will add them in the TypeScript file for this component):

```
    <div class="sample-tutorial">
        <gc-spread-sheets [backColor]="spreadBackColor" [hostStyle]="hostStyle" (workbookInitialized)="workbookInit($event)">
            <gc-worksheet [name]="sheetName" [dataSource]="data">
                <gc-column dataField="Name" width=300></gc-column>
                <gc-column dataField="Category" [width]=columnWidth></gc-column>
                <gc-column dataField="Price" [width]=columnWidth formatter="$ #.00"></gc-column>
                <gc-column dataField="Shopping Place" [width]=columnWidth></gc-column>
            </gc-worksheet>
        </gc-spread-sheets>
        <div class="options-container">
            <div class="option-row">
                <div class="inputContainer">            
                    <input type="file" id="fileDemo" class="input" (change)="changeFileDemo($event)">
                    <br >
                    <input type="button" id="loadExcel" value="import" class="button" (click)="loadExcel($event)">
                </div>
                <div class="inputContainer">
                    <input id="exportFileName" value="export.xlsx" class="input" (change)="changeExportFileName($event)">
                    <input type="button" id="saveExcel" value="export" class="button" (click)="saveExcel($event)">
                </div>
            </div>
            <div class="option-row">
                <div class="group">
                    <label>Password:
                        <input type="password" id="password" (change)="changePassword($event)">
                    </label>
                </div>
            </div>
        </div>
    </div>
```

Before adding the functions in the TypeScript file, we can add the styles to the **src>app>app.component.css** file:

```
    .sample-tutorial {
        position: relative;
        height: 100%;
        overflow: hidden;
     }

     .sample-spreadsheets {
       width: calc(100% - 280px);
       height: 100%;
       overflow: hidden;
       float: left;
     }

     .options-container {
       float: right;
       width: 280px;
       padding: 12px;
       height: 100%;
       box-sizing: border-box;
       background: #fbfbfb;
       overflow: auto;
     }

     .sample-options {
       z-index: 1000;
     }

     .inputContainer {
       width: 100%;
       height: auto;
       border: 1px solid #eee;
       padding: 6px 12px;
       margin-bottom: 10px;
       box-sizing: border-box;
     }

     .input {
       font-size: 14px;
       height: 30px;
       border: 0;
       outline: none;
       background: transparent;
     }

     .button {
       height: 30px;
       padding: 6px 12px;
       width: 80px;
       margin-top: 6px;
     }

     .group {
       padding: 12px;
     }

     .group input {
       padding: 4px 12px;
     }
     body {
       position: absolute;
       top: 0;
       bottom: 0;
       left: 0;
       right: 0;
     }
```

## Set Up Code-Behind

We can now set up the TypeScript file that is used in the component in **src>app>app.component.ts**:

```
    import { Component, enableProdMode } from '@angular/core';
    import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
    import * as GC from "@grapecity/spread-sheets";

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      spread: GC.Spread.Sheets.Workbook;
      spreadBackColor = 'aliceblue';
      sheetName = 'Goods List';
      hostStyle = {
        width: 'calc(100% - 280px)',
        height: '500px',
        overflow: 'hidden',
        float: 'left'
      };
      data = [
        { Name: 'Apple', Category: 'Fruit', Price: 1, 'Shopping Place': 'Wal-Mart' },
        { Name: 'Potato', Category: 'Fruit', Price: 2.01, 'Shopping Place': 'Other' },
        { Name: 'Tomato', Category: 'Vegetable', Price: 3.21, 'Shopping Place': 'Other' },
        { Name: 'Sandwich', Category: 'Food', Price: 2, 'Shopping Place': 'Wal-Mart' },
        { Name: 'Hamburger', Category: 'Food', Price: 2, 'Shopping Place': 'Wal-Mart' },
        { Name: 'Grape', Category: 'Fruit', Price: 4, 'Shopping Place': 'Sun Store' }
      ];
      columnWidth = 100;

      constructor() {
        this.spread = new GC.Spread.Sheets.Workbook();
      }
      workbookInit(args: { spread: GC.Spread.Sheets.Workbook; }){
        this.spread = args.spread;
        let spread = this.spread;
        let sheet = spread.getActiveSheet();
      }
    }
```

This will set up the basic SpreadJS instance in an Angular app, but in our case, we still want to add Excel Import and Export capabilities to make it a true Excel viewer.

![Angular Excel XLSX Viewer](https://files.grapecity.com/gc-website-media/zdppded5/01-angular.png?width=500&height=231.54056517775751)

## Add Excel Import/Export Code

Now that the SpreadJS instance is set up, we can add some ExcelIO code to that same **src>app>app.component.ts** file. We need to make sure to provide access to the ExcelIO code and declare a variable we will use later at the top of that file with the other import lines:

```
    ...
    import * as ExcelIO from "@grapecity/spread-excelio";
    declare var saveAs: any;
    ...
```

Within the **AppComponent** class, we can initialize some more variables we will use. You can add this after the **hostStyle** initialization:

```
    hostStyle = {
      ...
    }
    importExcelFile: any;
    exportFileName = "export.xlsx";
    password: string = "";
```

Before we move on, we need to make sure we add a reference to the **src>assets>FileSaver.js** file in the **src>index.html** file:

```
    <!doctype html>
    <html style="height:100%;font-size:14px;" lang="en">
    <head>
      <meta charset="utf-8">
      <title>SpreadSheetsAngularCli</title>
      <base href="/">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="icon" type="image/x-icon" href="favicon.ico">
      <script src="./assets/FileSaver.js"></script>
    </head>
    <body>
      <app-root></app-root>
    </body>
    </html>
```

The next step is to add the functions that will be fired when the user changes the file for import and export and the password in the **src>app>app.components.ts** file in the **AppComponent** class:

```
    workbookInit(...) {
      ...
    }

    changeFileDemo(e: any) {
      this.importExcelFile = e.target.files[0];
    }
    changePassword(e: any) {
      this.password = e.target.value;
    }
    changeExportFileName(e: any) {
      this.exportFileName = e.target.value;
    }
```

Now we can add code for loading an Excel file into SpreadJS. In this case, we can also utilize a password when opening:

```
    loadExcel(e: any) {
      let spread = this.spread;
      let excelIo = new ExcelIO.IO();
      let excelFile = this.importExcelFile;
      let password = this.password;
      excelIo.open(excelFile, function (json: any) {
        let workbookObj = json;
        spread.fromJSON(workbookObj);
      }, function (e: any) {
          alert(e.errorMessage);
      }, { password: password });
    }
```

We can also save Excel files with passwords as well, and in the case of this SpreadJS instance, we are loading data initially, so we need to add the **includeBindingSource** option:

```
    saveExcel(e: any) {
      let spread = this.spread;
      let excelIo = new ExcelIO.IO();
      let fileName = this.exportFileName;
      let password = this.password;
      if (fileName.substr(-5, 5) !== '.xlsx') {
          fileName += '.xlsx';
      }
      let json = spread.toJSON({includeBindingSource: true});
      // here is excel IO API
      excelIo.save(json, function (blob: any) {
          saveAs(blob, fileName);
      }, function (e: any) {
          // process error
          console.log(e);
      }, { password: password });
    }
```

![Angular Excel XLSX Viewer](https://files.grapecity.com/gc-website-media/pyybdkhr/02-angular.png?width=500&height=232.63254113345522)

That is all that is needed to create an Excel viewer using SpreadJS in an Angular application!