要实现从getList()下载JSON响应数据并以CSV或Excel格式保存,可以按照以下步骤进行:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { saveAs } from 'file-saver';
import * as XLSX from 'xlsx';
@Injectable()
export class DownloadService {
constructor(private http: HttpClient) {}
getList() {
return this.http.get('your-api-url');
}
downloadCSV(data: any[], filename: string) {
const csvContent = this.convertToCSV(data);
this.saveToFile(csvContent, 'text/csv', filename);
}
downloadExcel(data: any[], filename: string) {
const excelContent = this.convertToExcel(data);
this.saveToFile(excelContent, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', filename);
}
private convertToCSV(data: any[]) {
// Convert JSON to CSV format
const csvRows = [];
const headers = Object.keys(data[0]);
csvRows.push(headers.join(','));
for (const row of data) {
const values = headers.map(header => {
const escaped = (''+row[header]).replace(/"/g, '\\"');
return `"${escaped}"`;
});
csvRows.push(values.join(','));
}
return csvRows.join('\n');
}
private convertToExcel(data: any[]) {
// Convert JSON to Excel format using XLSX library
const worksheet = XLSX.utils.json_to_sheet(data);
const workbook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
return excelBuffer;
}
private saveToFile(content: any, type: string, filename: string) {
const blob = new Blob([content], { type: type });
saveAs(blob, filename);
}
}
import { Component } from '@angular/core';
import { DownloadService } from './download.service';
@Component({
selector: 'app-download',
template: `
`
})
export class DownloadComponent {
constructor(private downloadService: DownloadService) {}
downloadCSV() {
this.downloadService.getList().subscribe(data => {
this.downloadService.downloadCSV(data, 'data.csv');
});
}
downloadExcel() {
this.downloadService.getList().subscribe(data => {
this.downloadService.downloadExcel(data, 'data.xlsx');
});
}
}
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { DownloadService } from './download.service';
import { DownloadComponent } from './download.component';
@NgModule({
imports: [HttpClientModule],
declarations: [DownloadComponent],
providers: [DownloadService],
exports: [DownloadComponent]
})
export class DownloadModule { }
现在,当用户点击"Download as CSV"按钮时,会将getList()的响应数据下载为CSV文件。点击"Download as Excel"按钮时,会将响应数据下载为Excel文件。