avatar

ShīnChvën ✨

Effective Accelerationism

Powered by Druid

Rich Text with ExcelJS

Tue Mar 07 2023

ExcelJS is a library to create Excel files in Node.js and the browser. It supports rich text formatting, such as bold, italic, underline, font color, font size, font name, and more.

Most tutorials on the Internet show how to decorate text with getCell() and getRow() methods. However, the getCell() and getRow() methods are used to get an existing cell or row. However, it is actually inconvenient to decorate text with these methods when you are creating a new worksheet, because you'll have to calculate the cell position.

In this tutorial, I will show you how to decorate text before you adding them to the row by using RichText, so you don't have to calculate the cell position.

Create a Worksheet with Rich Text

import * as ExcelJS from 'exceljs';

const users = [
  { name: 'Jack', age: 15 },
];

const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('Sheet1');

worksheet.columns = [
  {header: 'Name', key: 'name'},
  {header: 'Age', key: 'age'},
];

const rows:Array<any> = [];

// add data to the worksheet
for (const user of users){
  const rowData = {
    name: user.name,
    age: { // use RichText object to decorate text
      richText: [ // array of RichTextItem, will be joined in the cell
        {font: {name: 'Arial', family: 4, size: 14, color: {argb: 'FF00FF00'}}, text: user.age},
        {font: {name: 'Arial', family: 4, size: 14, color: {argb: 'FFFF0000'}}, text: ' (Green)'},
      ]
    },
  };
  rows.push(rowData);
}

worksheet.addRows(rows);

workbook.xlsx.writeFile('example.xlsx')
  .then(() => console.log('Workbook saved successfully!'))
  .catch((error) => console.error(error));

More Examples of Constructing RichText

rowData.field = {
  richText: [
    {'font': {'size': 12,'color': {'theme': 0},'name': 'Calibri','family': 2,'scheme': 'minor'},'text': 'This is '},
    {'font': {'italic': true,'size': 12,'color': {'theme': 0},'name': 'Calibri','scheme': 'minor'},'text': 'a'},
    {'font': {'size': 12,'color': {'theme': 1},'name': 'Calibri','family': 2,'scheme': 'minor'},'text': ' '},
    {'font': {'size': 12,'color': {'argb': 'FFFF6600'},'name': 'Calibri','scheme': 'minor'},'text': 'colorful'},
    {'font': {'size': 12,'color': {'theme': 1},'name': 'Calibri','family': 2,'scheme': 'minor'},'text': ' text '},
    {'font': {'size': 12,'color': {'argb': 'FFCCFFCC'},'name': 'Calibri','scheme': 'minor'},'text': 'with'},
    {'font': {'size': 12,'color': {'theme': 1},'name': 'Calibri','family': 2,'scheme': 'minor'},'text': ' in-cell '},
    {'font': {'bold': true,'size': 12,'color': {'theme': 1},'name': 'Calibri','family': 2,'scheme': 'minor'},'text': 'format'}
  ]
};

expect(ws.getCell('A1').text).to.equal('This is a colorful text with in-cell format');
expect(ws.getCell('A1').type).to.equal(Excel.ValueType.RichText);

References