单击前端Angular网页中的按钮时,我需要将SQL Server数据库表中的所有数据放入.csv
文件中。
我已经用C#编写了一个Web API,以访问SQL Server表中的所有数据并将其显示在我的网页中。单击页面上显示表中所有数据的按钮时,我需要能够下载.csv
文件。
export class EmployeeService {
url = 'https://localhost:44395/Api/Employee';
constructor(private http: HttpClient) { }
getAllEmployee(): Observable<Employee[]> {
return this.http.get<Employee[]>(this.url + '/AllEmployeeDetails');
}
}
保存
您可以使用软件包file-saver从blob下载文件。加载数据并生成一个CSV字符串,可以将其转换为blob对象。
npm i文件保护程序
npm i @ types / file-saver
app.component.ts:
import { saveAs } from 'file-saver'
download(){
// Variable to store data as CSV string
let csvStr = '';
// Fetch data from service
this.employeeService.getAllEmployee().subscribe(
response => {
// Manipulate data to generate CSV string
},error => {}
);
// Convert string to blob
var csvBlob = new Blob([csvStr], {
type: 'text/plain'
});
// Download
saveAs(csvBlob,'data.csv')
}
由于必须在角度应用程序中显示数据,所以最好的解决方案是将数据作为json发送,并使用以下npm包:https://www.npmjs.com/package/xlsx将json转换为xlsx文件或csv
这里是我为之编写的示例服务,只需创建此服务并在需要的地方调用该函数即可:
excel.service.ts
import { Injectable } from '@angular/core';
import * as XLSX from 'xlsx';
@Injectable({
providedIn: 'root'
})
export class ExcelService {
constructor() { }
jsonToExcelSheet(data: any[], file_name = 'temp.xlsx') {
const workBook = XLSX.utils.book_new(); // create a new blank book
const workSheet = XLSX.utils.json_to_sheet(data);
let wscols = [{ wpx: 150 }, { wpx: 200 }, { wpx: 150 }, { wpx: 150 }];
workSheet['!cols'] = wscols; // set cell width
XLSX.utils.book_append_sheet(workBook, workSheet, 'data'); // add the worksheet to the book
return XLSX.writeFile(workBook, file_name); // initiate a file download in browser
}
jsonToCSV(data: any[], file_name = 'temp') {
const workBook = XLSX.utils.book_new(); // create a new blank book
const workSheet = XLSX.utils.json_to_sheet(data);
XLSX.utils.book_append_sheet(workBook, workSheet, 'data'); // add the worksheet to the book
return XLSX.writeFile(workBook, `${file_name}.csv`); // initiate a file download in browser
}
}
现在,如果要使用此服务,只需将其导入所需的component.ts
import { ExcelService } from 'src/services/excel.service';
constructor(private _excelService: ExcelService){}
async downloadWorksheet() {
let downloadData = {} // load your data here
// export the json as excelsheet
await this._excelService.jsonToExcelSheet(downloadData);
}