How to Import and Export Excel XLSX Using Angular

The Excel spreadsheet has been around since the 1980s. With over 30 million users, most are familiar with the Excel spreadsheet experience. Many businesses begin using Excel spreadsheets for budgeting and planning when their businesses are moderately simple.

At first, a small number of users may be involved in the process, and there may not be large quantities of data to interpret and organize. As the organization grows, it can be difficult to rely on Excel's functionalities.

Benefits of Using a Spreadsheet Component in an Application

A spreadsheet component can provide increased security, data consolidation, improved data visualization, strategic performance measurements (SPM), sophisticated statistical analysis, and more. Excel compatibility has been one of the most significant features of our Spread .NET and JavaScript components for years.

SpreadJS, our JavaScript component, offers a familiar Excel spreadsheet interface. You can import and export Excel files and even build your performance and business dashboards in JavaScript -- without any dependencies on Excel.

This article demonstrates how you can import and export Excel spreadsheets with SpreadJS in an Angular environment.

Here are the steps to import and export Excel spreadsheets in Angular: 

    1. Install the SpreadJS component in your application
    2. Instantiate the SpreadJS component
    3. Create an input element that accepts XLSX files
    4. Add import code
    5. Add export code

Try out this feature and many more. Download a trial of SpreadJS today!

Install the SpreadJS Component in Your Application

To follow along with this blog, download the sample here.

It should be noted that since we are working with the Angular CLI, we need to make sure that it is installed with NPM:

1npm install -g @angular/cli

Since we'll be working with SpreadJS’ Excel import and export functionality, we'll need the ExcelIO component. You can install that and the base SpreadJS files using NPM:

1npm install @grapecity/spread-sheets @grapecity/spread-excelio @grapecity/spread-sheets-angular

Instantiate the SpreadJS Component

SpreadJS can be added to the app.component.html page as:

<gc-spread-sheets [backColor]=”spreadBackColor” [hostStyle]="hostStyle" (workbookInitialized)="workbookInit($event)">
</gc-spread-sheets>

Instantiate the SpreadJS component and create an object of ExcelIO class in app.component.ts file with following code:

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

export class AppComponent {
  spreadBackColor = 'aliceblue';
  hostStyle = {
    width: '95vw',
    height: '80vh'
  };
  private spread;
  private excelIO;

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

  workbookInit(args: any) {
    const self = this;
    self.spread = args.spread;
    const sheet = self.spread.getActiveSheet();
    sheet.getCell(0, 0).text('Test Excel').foreColor('blue');
    sheet.getCell(1, 0).text('Test Excel').foreColor('blue');
    sheet.getCell(2, 0).text('Test Excel').foreColor('blue');
    sheet.getCell(3, 0).text('Test Excel').foreColor('blue');
    sheet.getCell(0, 1).text('Test Excel').foreColor('blue');
    sheet.getCell(1, 1).text('Test Excel').foreColor('blue');
    sheet.getCell(2, 1).text('Test Excel').foreColor('blue');
    sheet.getCell(3, 1).text('Test Excel').foreColor('blue');
    sheet.getCell(0, 2).text('Test Excel').foreColor('blue');
    sheet.getCell(1, 2).text('Test Excel').foreColor('blue');
    sheet.getCell(2, 2).text('Test Excel').foreColor('blue');
    sheet.getCell(3, 2).text('Test Excel').foreColor('blue');
    sheet.getCell(0, 3).text('Test Excel').foreColor('blue');
    sheet.getCell(1, 3).text('Test Excel').foreColor('blue');
    sheet.getCell(2, 3).text('Test Excel').foreColor('blue');
    sheet.getCell(3, 3).text('Test Excel').foreColor('blue');
 }

Angular

Create an Input Element That Accepts XLSX Files

For import, we'll create an input element that accepts XLSX files. Let’s add the following code in the app.component.html:

<div class='loadExcelInput'>
  <p>Open Excel File</p>
  <input type="file" name="files[]" multiple id="jsonFile" accept=".xlsx" (change)="onFileChange($event)" />
</div>

Add Import Code

The ExcelIO object opens the selected file and returns the result in JSON. This JSON data can be directly understood by SpreadJS, so we'll write the import code in the onFileChange() function for the change event as shown below:

onFileChange(args: any) {
  const self = this, file = args.srcElement && args.srcElement.files && args.srcElement.files[0];
  if (self.spread && file) {
    self.excelIO.open(file, (json: any) => {
      self.spread.fromJSON(json, {});
      setTimeout(() => {
        alert('load successfully');
      }, 0);
    }, (error: any) => {
      alert('load fail');
    });
  }
}

Add Export Code

Similarly, let’s add a button that will handle the export functionality. To add the export button, we can use:

<div class='exportExcel'>
  <p>Save Excel File</p>
  <button (click)="onClickMe($event)">Save Excel!</button>
</div>

We also need to handle the click event of this button and write our code there. SpreadJS saves the data as JSON and that JSON can be used by ExcelIO to save it as a BLOB. Later on, this blob data needs to be passed to the saveAs() function of the file-saver component:

onClickMe(args: any) {
  const self = this;
  const filename = 'exportExcel.xlsx';
  const json = JSON.stringify(self.spread.toJSON());
  self.excelIO.save(json, function (blob) {
    saveAs(blob, filename);
  }, function (error: any) {
    console.log(error);
  });
}

It should be noted that we have used the file-saver component for the export functionality. To include file-saver in your project, follow the steps below:

  1. Run the “npm install file-saver –save” command
  2. Run the “npm install @types/file-saver –save-dev” command
  3. Add this third-party lib to ‘.angular.json’
    1. 1"scripts": ["./node_modules/file-saver/FileSaver.js"]**
  4. Import the component
    1. 1import {saveAs} from 'file-saver'; 

Angular

You can now successfully import and export Excel files with SpreadJS in Angular. 

Try out this feature and many more. Download a trial of SpreadJS today!

If you have any questions, please leave a comment below. Check out our blog page for more articles like this, demos, videos, and tutorials.

Tags:

comments powered by Disqus