Custom Export based on filter on Angular Datatable

I wanted to export to CSV based on filtered data in a datatable in Angular 6. I have used angular datatable and it didn’t have the option yet although data table have the option.
So I created a custom function for exporting options using the HTML 5 feature.

Creating a Export Service

Create a file name export.service.ts under your app/services folder. If you don’t have the folder create it.Then copy paste the code given below.

  
    import {  Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})

export class ExportService {
    constructor() { }

    export (JSONData, Title, ShowLabel) {
        var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;

        var CSV = '';

        //CSV += Title + '\r\n\n';

        if (ShowLabel) {
            var row = "";
            for (var index in arrData[0]) {
                row += index + ',';

            }
            row = row.replace(/_/g, " ");
            row = row.slice(0, -1);
            CSV += row + '\r\n\n';
        }

        for (var i = 0; i < arrData.length; i++) {
            var row = "";
            for (var index in arrData[i]) {
                row += '"' + (arrData[i][index] != null ? arrData[i][index] : '') + '",';
            }

            row.slice(0, row.length - 1);

            CSV += row + '\r\n';
        }

        if (CSV == '') {
            alert("Invalid data");
            return;
        }
        var date = new Date(); 
        var fileName = "";
        fileName += Title.replace(/ /g, "_");
        //Initialize file format you want csv or xls
        var uri = 'data:text/csv;charset=utf-8,' + encodeURI(CSV);
        var link = document.createElement("a");
        link.href = uri;
        link.download = fileName +" "+ date.toLocaleDateString() + ".csv";
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

    }
    
    exportFiltered(tableId?: string,excelName?:string,columnsPrint?:any){
    let exportData = []
    let lengthtable = document.getElementById("divisionTable").getElementsByTagName("tr").length;
    let table = document.getElementById("divisionTable");
    let rows =table.getElementsByTagName("tr");
    for (var i=1; i < lengthtable; i++){
      let cells =rows[i].getElementsByTagName("td");
      let exportstring = "{\"S_NO\":"+ i +",";
      for(var j=0;j<columnsPrint.columns.length;j++)
      {
        exportstring += "\""+columnsPrint.columns[j]+"\":\""+cells[j+2].innerText+"\","; 
      }
        exportstring = exportstring.substring(0, exportstring.length - 1)+ "}";  
        let obj = JSON.parse(exportstring);
        console.log(obj)
        exportData.push(obj)
        console.log(i,exportstring)
    }
        this.exportService.export(exportData, excelName, true)
  }

}
  

Now you need to import the file where you want to use and call it in constructor

  
   import { DataTableDirective } from 'angular-datatables';

   @Component({
     selector: 'app-ListTable',
     templateUrl: './ListTable.component.html',
     styleUrls: ['./ListTable.component.css']
  })
export class ListTableComponent implements OnInit, OnDestroy {

  constructor( .......  exportService: ExportService) { }
  
  export(){
    let printColumns = {
      columns : [
        "DEPARTMENT NAME" ,
        "DEPARTMENT DESCRIPTION"
      ]
    }
    this.commonService.exportFiltered("TableId","SheetName",printColumns);
  
  }

}

  

Now in the html code you need to call the export function

  
#--- This is the code for Angular datatable which you must be using, You can follow the other post where I have mentioned how to use Angular datatable --- #
<app-component-header [valuesFromParent]="componentHeaderData" (click) = "export()"></app-component-header>

<table id="divisionTable" class="table table-padded">
<thead>
<tr>
<th class="printhide">Action</th>
<th class="printhide">S. No</th>
<th>Department Name</th>
<th>Department Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tdOption printhide"></td>
<td class="printhide" scope="row">{{i + 1}}</td>
<td>{{item.divisionName}}</td>
<td>{{item.divisionDescription}}</td>
</tr>
</tbody>
</table>
  

Leave a Reply

Your email address will not be published. Required fields are marked *

RSS
Follow by Email
Facebook
Twitter