Angular 2从getList()下载JSON响应数据并以CSV或Excel格式保存
创始人
2024-10-15 16:31:53
0

要实现从getList()下载JSON响应数据并以CSV或Excel格式保存,可以按照以下步骤进行:

  1. 创建一个Angular服务来处理数据下载和转换的逻辑。可以使用HttpClient来发送GET请求并获取JSON响应数据。在这个服务中,还需要使用第三方库来将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);
  }
}
  1. 在组件中使用该服务来获取数据并下载为CSV或Excel文件。
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');
    });
  }
}
  1. 在模块中声明和提供服务。
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文件。

相关内容

热门资讯

安装apache-beam==... 出现此错误可能是因为用户的Python版本太低,而apache-beam==2.34.0需要更高的P...
避免在粘贴双引号时向VS 20... 在粘贴双引号时向VS 2022添加反斜杠的问题通常是由于编辑器的自动转义功能引起的。为了避免这个问题...
Android Recycle... 要在Android RecyclerView中实现滑动卡片效果,可以按照以下步骤进行操作:首先,在项...
omi系统和安卓系统哪个好,揭... OMI系统和安卓系统哪个好?这个问题就像是在问“苹果和橘子哪个更甜”,每个人都有自己的答案。今天,我...
原生ios和安卓系统,原生对比... 亲爱的读者们,你是否曾好奇过,为什么你的iPhone和安卓手机在操作体验上有着天壤之别?今天,就让我...
Android - 无法确定任... 这个错误通常发生在Android项目中,表示编译Debug版本的Java代码时出现了依赖关系问题。下...
Android - NDK 预... 在Android NDK的构建过程中,LOCAL_SRC_FILES只能包含一个项目。如果需要在ND...
Akka生成Actor问题 在Akka框架中,可以使用ActorSystem对象生成Actor。但是,当我们在Actor类中尝试...
Agora-RTC-React... 出现这个错误原因是因为在 React 组件中使用,import AgoraRTC from “ago...
Alertmanager在pr... 首先,在Prometheus配置文件中,确保Alertmanager URL已正确配置。例如:ale...