I need to get all of the data in my SQL Server database table into a .csv
file when I click a button in a front end Angular web page.
I have already wr
Since you have to display the data in your angular application the best solution is to send the data as json and the use the following npm package : https://www.npmjs.com/package/xlsx to convert the json to xlsx file or csv
Here is a sample service i have written for the same, just create this service and call the function where you need it :
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
}
}
Now if you want to use this service just import it in the desired 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);
}