Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export PrimeNG DataTable to excel, pdf and xml

PrimeNG DataTable has a feature to export the data to a CSV file. I need to provide the functionality to export the data to Excel, PDF, and XML. How can I achieve this in my Angular2 application?

like image 858
Mohan Avatar asked Nov 09 '22 04:11

Mohan


1 Answers

PrimeNg does not support anything more than datatable to CSV natively. So you need to build this functionality from "scratch".

A good approach would be like this:

  1. You already have your data in a object in your compoment. This would be the object you pass in your datatable like this:

    <p-dataTable [value]="cars">

    so our data is at the cars object. At your compoment you can access it using

    this.cars

  2. The next step would be to add either to your datatable header or in any other part that suits your design a button that would read something in the lines of "download pdf" . Something like this:

    <p-button label="Click to download PDF" styleClass="ui-button-info" (click)="download()"></p-button>

    this will call the method download in your component when clicked

  3. Finally at the download method you need to convert your data to PDF or whatever other format you need. This can be easily done using one of the many libraries online, for example for PDF : jsPDF . An working example with angular can be found here: plunker example jsPDF angular4. So in our code we have inside the download function:

    let doc = new jsPDF();
    let col = ["Details", "Values"];
    let rows = [];
    for(let key in this.cars){
        let temp = [key, item[key]];
        rows.push(temp);
    }
    doc.autoTable(col, rows);
    doc.save('Test.pdf');
    
like image 98
Giannis Smirnios Avatar answered Nov 15 '22 07:11

Giannis Smirnios