Skip to main content Skip to footer

How to Add an Angular Excel XLSX Viewer to Your Web Application

Quick Start Guide
Tutorial Concept

Learn how to add an XLSX viewer to an Angular application.

What You Will Need
  • SpreadJS
  • VS Code
  • NPM
  • Angular 17
Controls Referenced

SpreadJS

As a client-side control, SpreadJS, our JavaScript spreadsheet, can be used with different frameworks, including Angular. This blog will use SpreadJS and Angular 17 to show you how to add an XLSX Viewer to your applications and allow your users to view Excel files easily.

Angular Excel Viewer

Download the sample to follow along.

Ready to Get Started? Download SpreadJS Today!

We will learn how to:

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

Create a New Project

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

ng new spreadjs-angular-cli --standalone=false
cd spreadjs-angular-cli

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

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

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

{
  ...
  "projects":{
    "spreadjs-angular-cli":{
      ...
      "architect":{
        ...
        "build":{
          ...
          options:{
            ...
            "styles": [
              "node_modules/@mescius/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 { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { SpreadSheetsModule } from "@mescius/spread-sheets-angular";

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, AppRoutingModule, FormsModule, 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">
              <label for="saveFileType">FileType:</label>
                <select id="saveFileType" [(ngModel)]="saveFileType">
                    <option value="sjs">SJS</option>
                    <option value="xlsx">Excel</option>
                    <option value="ssjson">SSJson</option>
                    <option value="csv">Csv</option>
                </select>
              <input type="button" id="saveExcel" value="export" class="button" (click)="saveExcel($event)">
          </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 } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import * as GC from "@mescius/spread-sheets";
import '@mescius/spread-sheets-io';
declare var saveAs: any;
import 'file-saver';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  title = 'spreadjs-angular-cli';

  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. We can run the app by simply using:

ng serve

The Angular viewer should be displayed as below:

Angular Excel XLSX Viewer

Add Excel Import/Export Code

Now that the SpreadJS instance is set up, we can add some of the SpreadJS IO code to that same src>app>app.component.ts file. We need to make sure to provide access to the Spread-Sheets-IO and File-Saver libraries:

...
import '@mescius/spread-sheets-io';
declare var saveAs: any;
import 'file-saver';
...

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

hostStyle = {
  ...
}
importExcelFile: any;
saveFileType: string = "sjs";

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

workbookInit(...) {
  ...
}

changeFileDemo(e: any) {
  this.importExcelFile = e.target.files[0];
}

getFileType(file: File) {
  if (!file) {
      return;
  }

  var fileName = file.name;
  var extensionName = fileName.substring(fileName.lastIndexOf(".") + 1);

  if (extensionName === 'sjs') {
      return 'sjs';
  } else if (extensionName === 'xlsx' || extensionName === 'xlsm') {
      return 'xlsx';
  } else if (extensionName === 'ssjson' || extensionName === 'json') {
      return 'ssjson';
  } else if (extensionName === 'csv') {
      return 'csv';
  } else {
    return;
  }
}

Now we can add code for loading an Excel file into SpreadJS. In this case, we can handle multiple file types:

loadExcel(e: any) {
  let spread = this.spread;
  let excelFile = this.importExcelFile;

  var fileType = this.getFileType(excelFile);
  if (fileType === 'sjs') {
    spread.open(excelFile, function() {}, function() {});
  } else {
    spread.import(excelFile, function() {}, function() {});
  }
}

We can also save Excel files 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 fileType = this.saveFileType;
  let fileName = 'export.' + fileType;

  if (fileType === 'sjs') {
    spread.save(function(blob: any) { saveAs(blob, fileName); }, function() {}, {includeBindingSource: true});
  } else if (fileType === 'xlsx') {//} || fileType === 'ssjson') {
    spread.export(function(blob: any) { saveAs(blob, fileName); }, function() {}, { fileType: GC.Spread.Sheets.FileType.excel, includeBindingSource: true });
  } else if (fileType === 'ssjson') {
    spread.export(function(blob: any) { saveAs(blob, fileName); }, function() {}, { fileType: GC.Spread.Sheets.FileType.ssjson, includeBindingSource: true });
  } else if (fileType === 'csv') {
    spread.export(function(blob: any) { saveAs(blob, fileName); }, function() {}, { fileType: GC.Spread.Sheets.FileType.csv, includeBindingSource: true });
  }
}

Excel viewer

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

Ready to check it out? Download SpreadJS Today!

comments powered by Disqus