Table of Contents
Exporting data to formats like CSV and Excel is a common requirement in Angular applications, especially for data analysis and reporting. Implementing these features allows users to download data directly from the application in a usable format. This article guides you through the steps to implement data export functionality to both CSV and Excel in Angular.
Setting Up Your Angular Project
Start by creating a new Angular project or opening an existing one. Ensure you have Angular CLI installed and your environment ready. You may also need to install additional libraries for Excel export, such as xlsx.
To install the xslx library, run:
npm install xlsx --save
Creating Export Functions
In your Angular component, import the necessary modules and define functions to generate CSV and Excel files.
import * as XLSX from 'xlsx';
@Component({
selector: 'app-data-export',
templateUrl: './data-export.component.html',
styleUrls: ['./data-export.component.css']
})
export class DataExportComponent {
data = [
{ id: 1, name: 'Alice', age: 30 },
{ id: 2, name: 'Bob', age: 25 },
{ id: 3, name: 'Charlie', age: 35 }
];
exportToCSV() {
const csvData = this.convertToCSV(this.data);
const blob = new Blob([csvData], { type: 'text/csv;charset=utf-8;' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'data.csv';
a.click();
window.URL.revokeObjectURL(url);
}
convertToCSV(objArray: any[]): string {
const header = Object.keys(objArray[0]).join(',') + '\r\n';
const rows = objArray.map(obj => Object.values(obj).join(',')).join('\r\n');
return header + rows;
}
exportToExcel() {
const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(this.data);
const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
XLSX.writeFile(workbook, 'data.xlsx');
}
}
Adding Export Buttons to the Template
In your component template, add buttons to trigger the export functions.
<button (click)="exportToCSV()">Export to CSV</button>
<button (click)="exportToExcel()">Export to Excel</button>
Conclusion
Implementing data export features in Angular enhances user experience by enabling easy data sharing and analysis. By using simple functions and libraries like xslx, you can efficiently add CSV and Excel export capabilities to your applications. Test your implementation thoroughly to ensure data accuracy and compatibility across formats.