3
const Excel = require('exceljs');
let workbook = new Excel.Workbook();
let workSheet = workbook.getWorksheet(1);
workSheet.getCell('W2').font = {color: {argb: "004e47cc"}};

this code sets font color for entire row, not just W2 cell. Same happens if I do:

let row2 = workSheet.getRow(2);
row2.getCell(23).font = {color: {argb: "004e47cc"}}; //W2

So how do I set cell style just for certain cell?

VladP
  • 881
  • 2
  • 13
  • 37

3 Answers3

2

It worked for me as well, but your code doesn't work as-is. workbook.getWorksheet(1) is failing, since you haven't created any worksheets in the new workbook you created.

This code generates a valid .xlsx file where cell W2 has the color you want:

const Excel = require('exceljs');
const workbook = new Excel.Workbook();
const workSheet = workbook.addWorksheet('Sheet');
workSheet.getCell('W2').font = {color: {argb: "004e47cc"}};
workbook.xlsx.writeFile('foo.xlsx');
Jim B.
  • 4,512
  • 3
  • 25
  • 53
0

Use "getWorksheet('sheetName')" instead of "getWorksheet(sheetNo)", This works fine for me.

Dipesh Gupta
  • 138
  • 1
  • 2
  • 10
0
  1. About styling:

This one should work properly:

row2.getCell(23).style = {font:{color: {argb: "004e47cc"}}}

Because, as a default all cells in a row referencing into one style object and the font is only a getter and setter to .style.font

  1. About accessing into worksheet:

Use "getWorksheet('sheetName')" instead of "getWorksheet(sheetNo)", This works fine for me.

So, in exceljs we provide two ways to get worksheet:

// FIRST:
// wb.getWorksheet(ws:string|number):Worksheet
wb.getWorksheet('sheetName')
wb.getWorksheet(sheetId) 
// NOTE: sheetId is number written into worksheet,
// it's not a index in array - just a number from Excel. 
// So for some files you read sheetId may be for instance: 10, 9, 999
// I recommend to avoid using  ws.getWorksheet(NUMBER).

// SECOND:
// wb.worksheets: Array<Worksheet>
wb.worksheets[1];
wb.worksheets[2];
wb.worksheets[wb.worksheets.lenght-1];
// I am big fan of using this way :)
  • I've just updated ExcelJs readme, I added some explanation about accessing to worksheet: https://github.com/exceljs/exceljs#access-worksheets – Paweł Siemienik May 10 '20 at 20:10