Home > Enterprise >  Google Apps Script - Change the background color of a cell Row (0), change the font style in Row (1)
Google Apps Script - Change the background color of a cell Row (0), change the font style in Row (1)

Time:09-22

I want to change the 1st cell backgroundcolor and 2nd cell font style but cannot seems to get it.

function insertHeading1(){
  var heading1Style = {};
  heading1Style[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
  heading1Style[DocumentApp.Attribute.FONT_SIZE] = 18;
  heading1Style[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.LEFT;
  heading1Style[DocumentApp.Attribute.LINE_SPACING] = 1;
  
  var cells = [
  ['#1c3a69', 'HEADING 1, CALIBRI, 18PT, BOLD, LEFT ALIGNED, ALL CAPS, SINGLE SPACING, NO SPACE BEFORE AND AFTER PARAGRAPH'],
  ];

  var tableRow1 = body.appendTable(cells);
  tableRow1.getCell(0,0).editAsText()
  .setBackgroundColor(0,1,'#1c3a69');
  tableRow1.getCell(0,1).editAsText
  .apply(heading1Style);
}

No errors, not sure what went wrong.

enter image description here

CodePudding user response:

In your script, how about the following modification?

From:

var tableRow1 = body.appendTable(cells);
tableRow1.getCell(0,0).editAsText()
.setBackgroundColor(0,1,'#1c3a69');
tableRow1.getCell(0,1).editAsText
.apply(heading1Style);

To:

tableRow1.setColumnWidth(0, 100);
tableRow1.getCell(0, 0).setBackgroundColor('#1c3a69');
tableRow1.getCell(0, 1).editAsText().setAttributes(heading1Style);

Or, if you want to set the font color of 1st cell to #ffffff, how about the following modification?

tableRow1.setColumnWidth(0, 100);
tableRow1.getCell(0, 0).setBackgroundColor('#1c3a69').editAsText().setForegroundColor("#ffffff");
tableRow1.getCell(0, 1).editAsText().setAttributes(heading1Style);
  • In this modification, your heading1Style is used. And, from your showing expected situation, in order to set the column width, tableRow1.setColumnWidth(0, 100) is used.

  • If you want to set heading1Style to the 1st cell, please modify to tableRow1.getCell(0, 0).setBackgroundColor('#1c3a69').editAsText().setAttributes(heading1Style) or tableRow1.getCell(0, 0).setBackgroundColor('#1c3a69').editAsText().setForegroundColor("#ffffff").setAttributes(heading1Style).

References:

  • Related