0

I am trying to add column headers when the user copies data from a ng2-handsontable. The before copy event fires and I am able to change the data in the event but it doesn't change what is copied to the clip board.

https://docs.handsontable.com/pro/1.14.2/Hooks.html#event:beforeCopy

This is the simplified version I am trying to get working first. I am always selecting all 4 columns.

private beforeCopy(e: any) {
    // e[0] is an array of the data
    // e[1] is an array of the coords
    var headers = ["Step 1", "Step 2", "Step 3", "Step 4"];
    e[0] = [headers, ...e[0]];
    e[1][0] = { endCol: headers.length-1, endRow: e[0].length-1, startCol: 0, startRow: 0};
}

Super simple version to test if can change the data at all:

private beforeCopy(e: any) {
    // e[0] is an array of the data
    // e[1] is an array of the coords
    e[0][0][0] = "test";
}

Both functions execute but in the end the data on the clipboard is still unedited data.

Calidus
  • 1,374
  • 2
  • 14
  • 31

1 Answers1

0

Angular Events are one directional, so editing the data in the event it self doesn't update the component that created the event. I found a couple solutions to copying the table headers:

  1. Remove the headers, and great a header row. Then user custom cell rendering to make that row read only, then the standard ctrl+a, ctrl+c will copy all the data and include the headers. https://docs.handsontable.com/0.15.0/demo-custom-renderers.html
  2. Override the copy function by writing your own and calling it in the afterCopy() function. This is difficult depending on the browsers you need to to support.
  3. Since my users are pasting data into excel, I made a export to csv function. It was rather easy using getData() and the following Post: How to export JavaScript array info to csv (on client side)?

   private export():void {
        var data:any = this.hot.getHandsontableInstance().getData();
        var csvContent:string = "data:text/csv;charset=utf-8,";
        csvContent += [...headers] + "\n";
        data.forEach(function (infoArray:any, index:number):void {
            var dataString:string = infoArray.join(",");
            csvContent += index < data.length ? dataString + "\n" : dataString;
        });
        var encodedUri:any = encodeURI(csvContent);
        var link:any = document.createElement("a");
        link.setAttribute("href", encodedUri);
        link.setAttribute("download", "data.csv");
        document.body.appendChild(link); // required for FF
        link.click();
    }
Calidus
  • 1,374
  • 2
  • 14
  • 31