Generating Excel File in Angular 9 using “ExcelJs” with Custom Font Family | Devstringx

Back to Blog
Excel File in Angular 9

Generating Excel File in Angular 9 using “ExcelJs” with Custom Font Family | Devstringx

Generate Excel Files in Angular 9

Let’s create a new Angular project using the Angular CLI tool by running/executing the following angular CLI command

  1. ng new export-to-excel
  2. Would you like to add Angular routing? Yes
  3. Which stylesheet format would you like to use? SCSS

What’s ExcelJS?

ExcelJS is the Javascript library used to read, write and manipulate the excel spreadsheet data and styles to JSON and XLSX. We can create XLSX files easily with formatted headers, footers, and cells, and input any custom data including text, images, etc. It’s an active and community-driven library with many features.

Features of ExcelJS

Here are some of the awesome features of Excel JS:-

Install ExcelJs

To install the ExcelJs package execute the following command, which is the main player to deal with Excel format-related functionalities we want to achieve

For more info or reference, you can check https://www.npmjs.com/package/exceljs this link.

Install FileSaver

We require FileSave.js to deal with operations like saving files on the disk. It is mainly used in web applications to store large files in the system.

Run the following command to install the file-saver

Configure tsconfig.json

Open the tsconfig.json file at the project root, then add the “paths” property under the “compiler options” with the “ExcelJs” library location

tsconfig.json

“compiler options”: {

…

“paths”: {

“exceljs”: [

“node_modules/exceljs/dist/exceljs.min”

]}}

Image to search font setting

Create a Service For ExcelJs

Now we’ll create a new service to keep the Excel-related method in one place so that we don’t have to write the whole code again and again for one functionality. To generate an Excel service in the service folder execute the following command.

This will create an ExcelService under the services folder

Update the ExcelService

Now open the excel.service.ts file inside the services folder and make the following changes:

  • import { Workbook } from ‘ExcelJs’;
  • import * as fs from ‘time-saver;

We will create a separate method in excel.service.ts called generate excel().

Now we will give the Title to the excel File Like “User Data”

So, we will just declare a variable named Title and give value to it.

const title = ‘User Data’

now, we will set the header and values of the column randomly

let’s suppose we have a JSON like

const user-list = [

{

name: ‘Rakesh’,

designation: ‘Software Developer’,

address: ‘Delhi’,

gender: ‘Male’

},

{

name: ‘Kapil’,

designation: ‘QA’,

address: ‘Noida’,

gender: ‘Male’

}, {

name: ‘Sunita’,

designation: ‘HR’,

address: ‘Gurgaon’,

gender: ‘Female’

}

]

For setting the header randomly from the keys of JSON, we will use

const header = Object.keys(userList[0])

This will take all the keys from the 0 index from the JSON and then the Object. keys() method will return the keys of the 0 index from the JSON into the header variable in the form of an array.

Create Workbook and Add a Worksheet

Create a new workbook and add a new worksheet using add worksheet() method of Workbook.

  • const workbook = new Workbook()
  • const worksheet = workbook. add worksheet(‘User Report’)

Good to Read:- Angular Project Setup by Angular CLI Tool

Add Rows and Format the Fonts

Now, we want to use the “Custom Font” Family in the Excel file so first, we will download the custom font from the web. For example, I want to use Saysettha OT font in our Excel file so I will download this font from https://laoscript.net/download/ this link.

Note: You can download any font from any website, you just need to install it in the system, we will tell you how to install the font in the system below

After downloading the font, let’s install the font in the system

Image to search font setting

2. Now drag and drop the download file below the Add Fonts section

Download and Add Font Sections

After dropping the font file, the system will automatically install the font in the system and you can check this font in the Excel sheet in the font dropdown.

Adding Custom Font to the Project

Add custom inside excel font folder

  • Now we have to add a font face to bind the download file with a name so that we can use it in the entire application
  • Go to the index.html page and then add
<style>
@font-face {

font-family: ‘Saysettha OT’;

src:

url(‘./assets/fonts/excelfont/saysettha_ot.ttf’) format(‘truetype’);}

</style>

It will look like this

Generating Excel File Angular 09

Let’s Resume to the excel.service.ts now

1. Let’s add a title row with our custom font

const title row = worksheet.addRow([title])

title row.font = { name: ‘Saysettha OT’, family: 4, size: 16, bold: true }

It will add a row with the title that we have provided above with our custom font family, here the name represents the name of the font family that we want to use in the Excel file, we have added our custom font with the font-face Saysettha OT.

Note: Make sure you must enter the exact value in the name that you have entered in the font-family attribute inside the @font-face

2. Adding Header in a new row with custom font

worksheet.addRow([])

const headerRow = worksheet.addRow(header)

headerRow.eachCell(cell => {

cell.font = { name: ‘Saysettha OT’, bold: true }

}

Note: you must give a custom font to every row

3. Add Data in Excel with a custom font

userList.forEach(d => {

let row = worksheet.addRow(Object.values(d))

row.font = { name: ‘Saysettha OT’ }

})

Export File Using FileSaver

workbook.xlsx.writeBuffer().then(excelData => {

const blob = new Blob([excelData], { type: ‘application/vnd.openxmlformats-officedocument.spreadsheetml.sheet’ })

fs.saveAs(blob, ‘UserReport.xlsx’)

})

Good to Read:- How To Use Google Maps In Your Angular Application

Your final code will look like this

tsconfig.js

{

“compileOnSave”: false,

“compilerOptions”: {

“baseUrl”: “./”,

“outDir”: “./dist/out-tsc”,

“sourceMap”: true,

“declaration”: false,

“downlevelIteration”: true,

“experimentalDecorators”: true,

“module”: “esnext”,

“moduleResolution”: “node”,

“importHelpers”: true,

“target”: “es2015”,

“lib”: [

“es2018”,

“dom”

],

“paths”: {

“exceljs”: [

“node_modules/exceljs/dist/exceljs.min”

]

}

},

“angularCompilerOptions”: {

“fullTemplateTypeCheck”: true,

“strictInjectionParameters”: true

}

}

app.component.ts

import { Component } from ‘@angular/core’;

import { ExcelService } from ‘./excel.service’;

@Component({

selector: ‘app-root’,

templateUrl: ‘./app.component.html’,

styleUrls: [‘./app.component.css’]

})

export class AppComponent {

constructor(private excelService: ExcelService) {}

generateExcel() {

this.excelService.generateExcel();

}

}

app.component.html

<button (click)=”generateExcel()”> Generate Excel</button>

Banner on Hire Our Angular Developer

excel.service.ts

import { Injectable } from ‘@angular/core’

import { Workbook } from ‘exceljs’

import * as fs from ‘file-saver’

@Injectable({

providedIn: ‘root’

})

export class ExcelService {

constructor() { }

generateExcel() {

const userList = [

{

name: ‘Rakesh’,

designation: ‘Software Developer’,

address: ‘Delhi’,

gender: ‘Male’

},

{

name: ‘Kapil’,

designation: ‘QA’,

address: ‘Noida’,

gender: ‘Male’

}, {

name: ‘Sunita’,

designation: ‘HR’,

address: ‘Gurgaon’,

gender: ‘Female’

}

]

const title = ‘User Data’

const header = Object.keys(userList[0])

const workbook = new Workbook()

const worksheet = workbook.addWorksheet(‘User Report’)

// Add new row

const titleRow = worksheet.addRow([title])

// Set font family, font size, and style in title row.

titleRow.font = { name: ‘Saysettha OT’, family: 4, size: 16, bold: true }

// Blank Row

worksheet.addRow([])

// Add Header Row

const headerRow = worksheet.addRow(header)

// Cell Style : Fill and Border

headerRow.eachCell(cell => {

cell.font = { name: ‘Saysettha OT’, bold: true }

})

// Add Data and Conditional Formatting

userList.forEach(d => {

let row = worksheet.addRow(Object.values(d))

row.font = { name: ‘Saysettha OT’ }

})

workbook.xlsx.writeBuffer().then(excelData => {

const blob = new Blob([excelData], { type: ‘application/vnd.openxmlformats-officedocument.spreadsheetml.sheet’ })

fs.saveAs(blob, ‘UserReport.xlsx’)

})

}

}

FAQs

1) How to Use Excel JS In Angular?

Here’s how to import and export Excel spreadsheets in Angular.

  • Install the SpreadJS component in your application
  • Instantiate a SpreadJS component
  • Create an input element that accepts an XLSX file
  • Add the import code
  • Add the export code

2) How to Read Data from an Excel File In Angular 12?

// Create workbook object let wb:Workbook = new Workbook(); The Workbook object must use readFile and file types. where xlsx is the file type. Create a prompt to get a value from the workbook, then block and fix it.

3) How do Download an Excel File From the Assets Folder in Angular?

To download an item, follow these steps:

  • Click on the logo in the upper left corner
  • On the browse page, click Assets > Files
  • Navigate to the folder containing the resource you want to download
  • Select a folder or select one or more assets in a folder
  • Click Download on the toolbar

If you are interested in even more development-related articles and information from us here at Devstringx, then we have a lot to choose from.

Share this post

Back to Blog