Angular 2从getList()下载JSON响应数据并以CSV或Excel格式保存
创始人
2024-10-15 16:31:28
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文件。

相关内容

热门资讯

透视详细!德州透视插件(透视)... 透视详细!德州透视插件(透视)hh poker软件,教程策略(存在有挂)-哔哩哔哩在进入德州透视插件...
透视辅助!sohoo poke... 透视辅助!sohoo poker辅助(透视)wepoker怎么提高运气,教程学习(有挂解密)-哔哩哔...
透视科普!hhpoker有透视... 透视科普!hhpoker有透视功能吗(透视)hhpoker德州真的假的,教程诀窍(了解有挂)-哔哩哔...
透视揭露!pokerrrr2辅... 透视揭露!pokerrrr2辅助(透视)wepoker辅助透视软件,教程资料(有挂攻略)-哔哩哔哩1...
透视教你!智星德州插件怎么下载... 透视教你!智星德州插件怎么下载(透视)aapoker脚本,教程手册(有挂攻略)-哔哩哔哩1、智星德州...
透视解密!约局吧辅助器(透视)... 透视解密!约局吧辅助器(透视)pokemmo内置修改器,教程指南书(真是有挂)-哔哩哔哩1、poke...
透视推荐!福建大菠萝万能辅助器... 透视推荐!福建大菠萝万能辅助器(透视)wepokerplus到底是挂了吗,教程模块(有挂技术)-哔哩...
透视解迷!uupoker有透视... 透视解迷!uupoker有透视吗(透视)德普之星透视,教程妙招(有挂教学)-哔哩哔哩1、透视解迷!u...
透视开挂!wepokerplu... 透视开挂!wepokerplus透视脚本免费(透视)德普辅助软件,教程手册(真实有挂)-哔哩哔哩1、...
透视解谜!德普之星辅助器app... 透视解谜!德普之星辅助器app(透视)拱趴大菠萝开挂方法,教程技法(证实有挂)-哔哩哔哩1)拱趴大菠...