handsOnTable cell coloring

2019-04-12 04:12发布

问题:

I have a Handsontable table filled with data and already rendered

After checking the cells, I have located a couple of cells of interest and would like to color them - is there a good way to do this using the Handsontable code?

Please note this is after loading and rendering the table

Edit:

The table is rendered with basic options:

$container.handsontable({
    startRows: 8,
    startCols: 6,
    rowHeaders: true,
    colHeaders: true,
    minSpareRows: 1,
    minSpareCols: 1,
    //contextMenu: false,
    cells: function (row, col, prop) {
    }
  });

And the data is loaded via Ajax, decode_file.php reads an excel sheet and returns data as JSON:

  $.ajax({
      url: "decode_file.php",
      type: 'GET',
      success: function (res) {
        handsontable.loadData(res.data);
        console.log('Data loaded');
      },
      error: function (res) {
        console.log("Error : " + res.code);
      }
    });

After loading the data, the user clicks a "Process" button and the code looks for a cell with the text "Hello world". Let's say the code finds the text "Hello World" in cell row 4/col 5 and changed the background color of cell row 4/col 5 to red

回答1:

The homepage provides a good example for your purpose:

http://handsontable.com/demo/renderers.html

Just modify the condition (in this case upper/left corner).

cells: function (row, col, prop) {
  if (row === 0 && col === 0) {
    return {type: {renderer: greenRenderer}};
  }
}

and you're done.



回答2:

  1. get the coordinates of the selected cell(s) using handsontable('getSelected')

  2. if the selection is not empty :

    a. loop on all cells to gather each cell's renderer using handsontable('getCellMeta') and meta.renderer, then store them in an array (this should be done only once)

    b. update the table using handsontable("updateSettings") and cellProperties.renderer :

    • for cells within the selected coordinates, apply the chosen renderer and update the renderer's name in the 2.a. array

    • for all other cells, apply the stored renderer



回答3:

One a bit strange method that I'm using, and it actually fast and works fine:

afterRender: function(){
    render_color(this);
}

ht is the instance of the handsontable, and render_color:

function render_color(ht){
  for(var i=0;i<ht.countRows();i++){
    for(var p=0;p<ht.countCols();p++){
      cell_color = "#000";
      font_color = "#fff";
      $(ht.getCell(i,p)).css({"color": font_color, "background-color": cell_color})
    }
  }
}