How to export data to excel sheet with colors and style in angular.
There are two most popular library for javascript to export data with excel sheet.
1) xlsx library
2) exceljs library
If you would like to export simple data without changing its style then xlsx is perfact, but if you would like to change style before export then exceljs is perfect for JavaScript frameworks.
Lets create an example with exceljs library to export data by changing style and colors for angular.
Step 1: Install "exceljs" library
npm install exceljs
Step 2: Install "file-saver" library to save excel file.
npm install file-saver
Step 3: Import "exceljs" and "file-saver" library to your component.
import * as ExcelJS from 'exceljs/dist/exceljs.min.js';
import { saveAs } from 'file-saver';
Step 4: Now create function in your component to export Data.
exportExcel()
{
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('My Sheet');
let dataArray = [{'Surname':'Lakhani','Name':'Ali'},
{'Surname':'Lakhani','Name':'Raza'},
{'Surname':'Patel','Name':'Nikunj'},
{'Surname':'Patel','Name':'Jigar'}];
// Add headers
const headers = Object.keys(dataArray[0]);
let headerRow = worksheet.addRow(headers);
headerRow.font = {bold:true};
// Add data rows
dataArray.forEach((item,index) => {
let row = [];
headers.forEach((header) =>
{
row.push(item[header]);
});
let row1 = worksheet.addRow(row);
const isEvenRow = index % 2 === 0;
const fillColor = isEvenRow ? 'DDDDDDDD' : 'FFFFFFFF';
row1.fill = {
type: 'pattern',
pattern: 'solid',
fgColor: { argb: fillColor }
};
});
worksheet.getColumn(1).width = 20;
worksheet.getColumn(2).width = 20;
// Generate Excel file
workbook.xlsx.writeBuffer().then((buffer: any) => {
const blob = new Blob([buffer],
{ type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
saveAs(blob, 'Friends.xlsx');
});
}
Step 4: Now call above function in ngOnInint to execute it.
Suggesion: "exceljs" library is created for backend nodejs framework,
So don't try to import directly exceljs.
import * as ExcelJS from 'exceljs'; //Wrong way to import exceljs in angular, it will throw bellow error.
"Cannot find module 'stream' or its corresponding type declarations.",
import * as ExcelJS from 'exceljs/dist/exceljs.min.js'; //Correct way to import in angular.
If you still want to use "exceljs" directly then Add "types": ["node"] option to the compilerOptions section in your tsconfig.app.json file, it will resolve the error.
Comments
Post a Comment