c# - 有没有办法在 Angular 中单击按钮时从 SQL Server 数据库表中下载数据的 csv 文件
问题描述
.csv
当我单击前端 Angular 网页中的按钮时,我需要将我的 SQL Server 数据库表中的所有数据放入一个文件中。
我已经用 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');
}
}
节省
解决方案
由于您必须在 Angular 应用程序中显示数据,因此最好的解决方案是将数据作为 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);
}
推荐阅读
- regex - 为什么 Perl 正则表达式 \K 不排除 \K 之前匹配的模式?
- mysql - 如果点与它相交,请指定位置名称 MySQL
- php - 正则表达式:在一个词组中捕获多个实例
- python - 如何打包适用于 iOS 的 Kivy 应用程序?
- java - 如何使用 Mockito/Powermock 使用构造函数参数测试类的方法
- node.js - cpanel node.js 无法获取应用程序的锁:应用程序
- angular - 如何动态访问 angular.html 中定义的模板引用变量(符号:#)
- r - 使用带状置信区间可视化两个分类预测变量和连续结果之间的交互
- c - 乘以 3x3 矩阵的函数仅对中间列给出错误答案
- python - 相同的 BSD 套接字 API 程序适用于 Python,但不适用于 C++ 或 Rust