What You Will Need
- SpreadJS
- NPM
- Angular v16
- Visual Studio Code
Controls Referenced
Tutorial Concept
Import/Export CSV Angular - Add the functionality to import and export CSV files in an Angular spreadsheet application using SpreadJS features.
In the dynamic world of web development, Angular stands out as a powerful framework. As Angular developers, we frequently handle data in various formats, with CSV files a common requirement. Whether it's importing data from external sources, performing data analysis, or presenting information in a structured format, mastering CSV file manipulation is crucial. In this blog, we'll delve into handling CSV files using SpreadJS, a robust spreadsheet component for Angular. You'll learn how to import, visualize, and export CSV data seamlessly within an Angular application. Let's explore the capabilities of effortless CSV file management in Angular development.
Steps to Import and Export CSV Files in an Angular Spreadsheet Application
- Add SpreadJS to an Angular App
- Add Buttons for Import and Export
- Import CSV Data to Angular App Using SpreadJS’s setCsv Method
- Export Angular Data to a CSV File Using SpreadJS’s getCsv Method
To follow along with this tutorial, you can download the sample.
Add SpreadJS to an Angular App
To get started with this example, create an angular app, reference SpreadJS’s files, and initialize the JavaScript spreadsheet component. In this case, we can use NPM to install the required SpreadJS files:
npm install @mescius/spread-sheets @mescius/spread-sheets-angular
We can now add the component to our app.component.html file for SpreadJS:
<gc-spread-sheets [hostStyle]="hostStyle" (workbookInitialized)="workbookInit($event)"></gc-spread-sheets>
Then, in our app.component.ts file, we can add the imports that we will need:
import { Component } from '@angular/core';
import * as GC from "@mescius/spread-sheets";
import { SpreadSheetsModule } from "@mescius/spread-sheets-angular";
import { saveAs } from "file-saver";
We can then define the decorator and the variables for the component:
@Component({
selector: 'app-root',
standalone: true,
imports: [SpreadSheetsModule],
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
spread: GC.Spread.Sheets.Workbook | null = null;
hostStyle = {
width: '800px',
height: '600px'
};
}
After that, we can add the initialization function for SpreadJS that we are referencing in the HTML file inside of the class definition:
workbookInit(args: { spread: GC.Spread.Sheets.Workbook; }) {
this.spread = args.spread;
}
This is how the SpreadJS instance should look:
Add Buttons for Import and Export
Next, we can add a button and a file selector element to our HTML page:
<input type="file" (change)="onFileChange($event)"/>
<button (click)="onExportCSV()">Export</button>
We then add the functions connected to these elements as well. For the export, we will add this function later in this blog, but for now, we need to add the event code for changing the file:
onFileChange(event: Event) {
const input = event.currentTarget as HTMLInputElement;
this.importCSV(input);
}
In this code, we simply retrieve the input from the event and pass it to the CSV importing function, which we will define in the next section. After adding the buttons, our page should look like this:
Import CSV Data to Angular App Using SpreadJS’s setCsv Method
To import CSV data, invoke SpreadJS’s setCsv method within the importCSV function. The setCsv method has a rowDelimiter and columnDelimiter as the fourth and fifth parameters, respectively. These can be changed to different symbols, like changing the columnDelimiter from “,” to “\t”, which will support TSV files as well. In the case of this example, we are just going to use commas. We need to retrieve the file from the input, read it as text, and then use setCsv:
importCSV(fileInput: HTMLInputElement) {
if (fileInput.files && fileInput.files[0]) {
let reader = new FileReader(), that = this;
reader.onload = function (event: any) {
let csv = event.target.result;
that.spread?.getSheet(0).setCsv(0, 0, csv,'\r\n', ",");
}
reader.readAsText(fileInput.files[0])
}
}
Export Angular Data to a CSV File Using SpreadJS’s getCsv Method
Alternatively, to export CSV data, we need to use the getCsv method within the exportCSV function. We can retrieve the CSV content with the getCsv method and then save it as a Blob type:
onExportCSV() {
let sheet = this.spread?.getActiveSheet();
if (sheet) {
let usedRange: GC.Spread.Sheets.Range = sheet.getUsedRange(GC.Spread.Sheets.UsedRangeType.data);
let csv = sheet.getCsv(usedRange.row, usedRange.col, usedRange.rowCount, usedRange.colCount, "\r\n", ",");
let blob = new Blob([csv], { type: "text/plain;charset=utf-8" });
saveAs(blob, 'export-' + new Date().valueOf() + '.csv');
}
}
That’s all that is needed to import and export CSV files with SpreadJS:
Conclusion
With a small amount of SpreadJS code, you can add CSV import and export functionality to your Angular app, providing your users the ability to load and save their data. For more information about SpreadJS and examples, check out our Demos and Documentation.
Top comments (0)