1. **Install the Required Libraries**:
Install the `xlsx` library using npm or yarn:
```bash
npm install xlsx
```
2. **Create a Service**:
Create a service that handles the export functionality. Let's call it `excel.service.ts`.
```typescript
import { Injectable } from '@angular/core';
import * as XLSX from 'xlsx';
@Injectable({
providedIn: 'root'
})
export class ExcelService {
exportToExcel(data: any[], filename: string, sheetName: string): void {
const ws: XLSX.WorkSheet = XLSX.utils.json_to_sheet(data);
const wb: XLSX.WorkBook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, sheetName);
XLSX.writeFile(wb, filename + '.xlsx');
}
}
```
3. **Use the Service in a Component**:
In your component, inject the `ExcelService` and call the `exportToExcel` method when you want to export your JSON data.
```typescript
import { Component } from '@angular/core';
import { ExcelService } from './excel.service';
@Component({
selector: 'app-root',
template: `
<button (click)="exportToExcel()">Export to Excel</button>
`
})
export class AppComponent {
data: any[] = [
{ name: 'John', age: 28, city: 'New York' },
{ name: 'Jane', age: 24, city: 'Los Angeles' },
// Add more data here...
];
constructor(private excelService: ExcelService) {}
exportToExcel(): void {
this.excelService.exportToExcel(this.data, 'data', 'Sheet1');
}
}
```
4. **Styling and Enhancements**:
The above example provides a basic way to export JSON data to an Excel file in an Angular application. Depending on your requirements, you might want to enhance this process by adding loading indicators, error handling, or allowing users to customize the exported data.
Remember to adjust the code according to your specific needs and the structure of your Angular application. Always ensure you handle any potential errors and provide a good user experience.