Code to implement export to excel in Angular app.
interface ExcelRow<T> {[key: string]: T;}
interface Column<T> {
header: string;
key: keyof T;
type: 'string' | 'number';
}
exportToExcel() {
const maxLength: Record<string, number> = this.columns.reduce(
(acc: Record<string, number>, col: Column<ExcelRow<number | string>>) => {
acc[col.key] = 0;
return acc;
},
{}
);
this.data.forEach((data: ExcelRow<number | string>) => {
this.columns.forEach((column: Column<ExcelRow<number | string>>) => {
const val: string | number = data[column.key];
const length: number = ('' + val).toString().length;
maxLength[column.key] = Math.max(maxLength[column.key], length);
});
});
const colWidths: Record<string, string> = this.columns.reduce(
(acc: Record<string, string>, col: Column<ExcelRow<number | string>>) => {
acc[col.key] = `${maxLength[col.key] * 80}%`;
return acc;
},
{}
);
let htmlContent = `
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<table border="1">
<tr>
${this.columns
.map(
(column: Column<ExcelRow<number | string>>) =>
`<th style="width: ${colWidths[column.key]}">${
column.header
}</th>`
)
.join('')}
`;
this.data.forEach((data: ExcelRow<number | string>) => {
htmlContent += `
</tr>
${this.columns
.map(
(column: Column<ExcelRow<number | string>>) => `
<td>${data[column.key]}</td>
`
)
.join('')}
`;
});
htmlContent += `
</table>
</body>
</html>
`;
Example column and data to export -
data: ExcelRow<number | string>[] = [
{
id: 7,
name: 'John Doe',
work: 'Developer',
address: '7, Village Road, KA',
},
{
id: 8,
name: 'Alice',
work: 'QA Engg',
address: '7, Village Road, LA',
},
{
id: 9,
name: 'Maya',
work: 'Manager',
address: '7, Village Road, MH',
},
];
columns: Column<ExcelRow<number | string>>[] = [
{
header: 'ID',
key: 'id',
type: 'number',
},
{
header: 'Name',
key: 'name',
type: 'string',
},
{
header: 'Work',
key: 'work',
type: 'string',
},
{
header: 'Address',
key: 'address',
type: 'string',
},
];
Follow the below example implemented in stackblitz for exporting array of objects without using any library.
Top comments (0)