Quick Start Guide | |
---|---|
Tutorial Concept | Learn how to import, modify, and export Excel (.xlsx) files in Angular applications. |
What You Will Need |
Angular 16 Visual Studio Code |
Controls Referenced |
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.
Ready to Try It Out? Download SpreadJS Today!
How to Import and Export Excel (.XLSX) Files in Angular Applications
- Create an Angular Spreadsheet Application
- Add Excel Import Code
- Add Data to the Imported Excel File
- Add Excel Export Code
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
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 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"
],
…
}
…
}
…
}
…
}
}
…
}
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;
}
In the app.component.ts file, add the following code to add the Angular spreadsheet 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:
Add Excel Import Code to an Angular App
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();
}
...
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 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);
}
With these steps, you've successfully add Excel import functionality to the Angular spreadsheet application.
Add Data to the Import Excel 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 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;
}
Notice, that when the button is clicked, new customer data is added to the statement, and the formulas within the worksheet update accordingly.
Add Excel Export Code to an Angular App
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
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.
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.
Ready to Try It Out? Download SpreadJS Today!
To learn more about SpreadJS and the new latest release features, check out our release pages releases and this video:
In another article series, we demonstrate how to import/export Excel (.xlsx) spreadsheets in other frameworks: