我正在学习Angular 2,我试图通过使用web api从sql server表中获取客户数据来下载角度为2的Excel文件。
在谷歌搜索后,我发现了一些代码,但是使用了该代码,我发现了一个错误,例如'无法找到模块xlsx的声明文件'
我已安装在
下面npm install xlsx --save
npm install file-saver --save
以下是我使用过的代码:
下载组件
import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';
import { Component, EventEmitter, Input,Injectable, Inject, enableProdMode, AfterViewInit, NgModule } from '@angular/core';
import { ResponseContentType } from '@angular/http';
import {HttpService} from '../http.service';
import { AppModule } from '../app.module';
import { CommonModule } from '@angular/common';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { BrowserModule } from '@angular/platform-browser';
const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
const EXCEL_EXTENSION = '.xlsx';
import 'rxjs/Rx' ;
@Component ({
selector: 'my-app',
templateUrl:'./excelDownload.html',
providers:[HttpService]
})
@Injectable()
export class ExcelDownloadComponent {
constructor(private httpService: HttpService )
{
}
public exportAsExcelFile(json: any[], excelFileName: string): void {
const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'buffer' });
this.saveAsExcelFile(excelBuffer, excelFileName);
}
private saveAsExcelFile(buffer: any, fileName: string): void {
const data: Blob = new Blob([buffer], {
type: EXCEL_TYPE
});
FileSaver.saveAs(data, fileName + '_export_' + new Date().getTime() + EXCEL_EXTENSION);
}
GetRemindersData()
{
var Flag="ALL_SPOTCHECK_RECORDS";
this.httpService.GetRemindersData(Flag).subscribe(
data=>this.exportAsExcelFile((data[1]),"Spot_Check"),
error => console.log("Error downloading the file."),
() => console.info("OK"));
}
}
Http service.ts
import { ResponseContentType } from '@angular/http';
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import {Observable} from 'rxjs/Rx';
// Import RxJs required methods
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class HttpService {
constructor( private http: Http) { }
public GetRemindersData(Flag:string){
var GetRemindersData_URL:string = 'http://localhost:5000/api/RemindersData/?Flag='+Flag;
return this.http.get(`${GetRemindersData_URL}`)
.map((res:Response) => res.json())
.catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}
}