Search code examples
javascripthandsontable

How to copy data of html formatted cell instead of markup


I have some cells in Handsontable, that are displayed using "html" renderer. When I copy these cells and paste them in Excel, I get html content instead of data. Is there a way to display cells as they are, and get their value when copying ?

JSFiddle example: example

document.addEventListener("DOMContentLoaded", function() {
    var
    data = [
      {
        title: "Title 1",
        description: "<div style='text-align:right'>148</div>"
      },
      {
        title: "Title 2",
        description: "<div style='text-align:right'>2002</div>"
      }
    ],
    container1,
    hot1;

    container1 = document.getElementById('example1');
        hot1 = new Handsontable(container1, {
        data: data,
        colWidths: [200, 200],
        colHeaders: ["Title", "Description"],
        columns: [
           {data: "title", renderer: "html"},
           {data: "description", renderer: "html"}
        ]
    });
});

Solution

  • You can try converting your input data into json format and have a custom renderer which displays the value from json. Add a toString property to the data which will return exactly what you want to get copied.

    Here is an updated fiddle: http://jsfiddle.net/mpusarla/gng4wqzy/6/

    document.addEventListener("DOMContentLoaded", function() {
      var item1 = {};
      item1.title = "Title 1 ";
      item1.description = {};
      item1.description.text = "Desc 1";
      item1.description.toString = function() {
        return 'Updated Desc for 1';
      }
    
      var item2 = {};
      item2.title = "Title 2";
      item2.description = {};
      item2.description.text = "Desc 2";
    
      item2.description.toString = function() {
        return 'Updated Desc for 2 ';
      }
    
      var data = [];
      data.push(item1);
      data.push(item2);
      var container1, hot1;
    
      function customRenderer(instance, td, row, col, prop, value, cellProperties) {
        td.innerHTML = '<div style="text-align:right">' + value.text;
      }
    
      container1 = document.getElementById('example1');
      hot1 = new Handsontable(container1, {
        data: data,
        colWidths: [200, 200],
        colHeaders: ["Title", "Description"],
        columns: [{
          data: "title",
          renderer: "text"
        }, {
          data: "description",
          renderer: customRenderer
        }]
      });
    });
    </style><!-- Ugly Hack due to jsFiddle issue --> <script src="http://docs.handsontable.com/0.15.0/scripts/jquery.min.js"></script> <script src="http://docs.handsontable.com/0.15.0/bower_components/handsontable/dist/handsontable.full.js"></script> <link type="text/css" rel="stylesheet" href="http://docs.handsontable.com/0.15.0/bower_components/handsontable/dist/handsontable.full.min.css">
    <div id="example1" class="hot handsontable"></div>