How to set the background colour of every cell in a HandsOnTable?

10,254

There are a variety of ways to accomplish this. However, the cells function is probably the best.

Option 1

Step 1: Set up your handsontable:

var container = document.getElementById('Element_ID');
hot = new Handsontable(container, {
  data: <yourdataArray>,
  autoRowSize:false,
  autoWrapRow:true,
  autoRowSize: false
});

Step 2: Update the handsontable settings using the cells function. The cells function will go through each row and cell in the table

 // update spreadsheet setting
 hot.updateSettings({
     cells: function (row, col, prop) {                        
          var cell = hot.getCell(row,col);   // get the cell for the row and column                                                                                                                
          cell.style.backgroundColor = "#EEE";  // set the background color
     }
 });

Option 2

I recommend the cells function over this, but this does demonstrate other ways of doing the same thing.

var hot = new Handsontable(document.getElementById('example1'), options);
var rows=hot.countRows();  // get the count of the rows in the table
var cols=hot.countCols();  // get the count of the columns in the table.
for(var row=0; row<rows; row++){  // go through each row of the table
    for(var col=0; col<cols; col++){  // go through each column of the row
        var cell = hot.getCell(row,col);  
        cell.style.background = "#00FF90";
    }
}
hot.render();  // ensure the table is refreshed.  
Share:
10,254
Matt W
Author by

Matt W

I write code for fun and profit. Sometimes I blog about it. Not enough time for either. At work I break websites. At home I break physics based mobile games. "No code more than 8 lines ever worked as intended first time." - My Dad.

Updated on July 15, 2022

Comments

  • Matt W
    Matt W almost 2 years

    I have a HandsOnTable table and would like to set the background colour of every cell, without providing a renderer function or the like. I tried copying the process that their Science demo uses but my table has formatting on the values and that gets lost with their renderer function code.

    My version of the renderer:

    var footerRenderer = function(instance, td, row, col, prop, value, cellProperties) {
        Handsontable.renderers.TextRenderer.apply(this, arguments);
        td.style.backgroundColor = '#EEE';
        td.style.textAlign = 'right';
    }
    

    To clarify: The problem here is that using a renderer function with HandsOnTable appear to wipe out formatting which has been applied by the properties of the table, when something simple like changing the background colour of a cell is required.