//HTML
<button onclick="exportToCsv()">export to CSV</button>
// Javascript
var Results = [
["Col1", "Col2", "Col3", "Col4"],
["Data", 50, 100, 500],
["Data", -100, 20, 100],
];
exportToCsv = function() {
var CsvString = "";
Results.forEach(function(RowItem, RowIndex) {
RowItem.forEach(function(ColItem, ColIndex) {
CsvString += ColItem + ',';
});
CsvString += "
";
});
CsvString = "data:application/csv," + encodeURIComponent(CsvString);
var x = document.createElement("A");
x.setAttribute("href", CsvString );
x.setAttribute("download","somedata.csv");
document.body.appendChild(x);
x.click();
}
import * as ExcelJS from 'exceljs';
function bufferToFile(
buffer,
filename,
type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
) {
let blob = new Blob([buffer], { type });
const anchor = document.createElement('a');
const url = URL.createObjectURL(blob);
anchor.href = url;
anchor.download = filename;
document.body.appendChild(anchor);
anchor.click();
document.body.removeChild(anchor);
URL.revokeObjectURL(url);
}
async function exportToExcel($event) {
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('My Sheet');
worksheet.columns = [
{ header: 'Id', key: 'id', width: 10 },
{ header: 'Name', key: 'name', width: 32 },
{ header: 'D.O.B.', key: 'DOB', width: 10, outlineLevel: 1 },
];
worksheet.getColumn(2).alignment = {
vertical: 'middle',
horizontal: 'center',
wrapText: true,
};
worksheet.addRow([3, 'Sam
Sung', new Date()]);
worksheet.addRow({
id: 1,
name: 'John Doe',
DOB: new Date(1994, 10, 10),
});
const filename = 'Export.xlsx';
const buffer = await workbook.xlsx.writeBuffer();
this.bufferToFile(buffer, filename);
}