primefaces / primeng

The Most Complete Angular UI Component Library
https://primeng.org
Other
10.55k stars 4.61k forks source link

DataTable - Export #894

Closed lylynguyen closed 7 years ago

lylynguyen commented 8 years ago

Is there anyway to make export results produce proper/custom filenames instead of download(#).csv?

cheng1994 commented 8 years ago

The way that I was able to solve this problem is to edit datatable.js in node-modules/primeng/components/datatable to this:

var _this = this;
        var data = this.value, csv = "data:text/csv;charset=utf-8,", tempCsv = "";

        //headers
        for (var i = 0; i < this.columns.length; i++) {
            if (this.columns[i].field) {
                tempCsv += this.columns[i].field;
                if (i < (this.columns.length - 1)) {
                    tempCsv += this.csvSeparator;
                }
            }
        }
        //body        
        this.value.forEach(function (record, i) {
            tempCsv += '\n';
            for (var i_1 = 0; i_1 < _this.columns.length; i_1++) {
                if (_this.columns[i_1].field) {
                    tempCsv += _this.resolveFieldData(record, _this.columns[i_1].field);
                    if (i_1 < (_this.columns.length - 1)) {
                        tempCsv += _this.csvSeparator;
                    }
                }
            }
        });
        var a = document.createElement('a');
        if (typeof a.download != "undefined") {
            var link = document.createElement("a");
            link.setAttribute("href", encodeURI(csv += tempCsv)); 
            link.setAttribute("download", filename + ".csv"); 
            document.body.appendChild(link); 
            link.click(); 
        } else {
            if(navigator.msSaveBlob) {
                blobObject = new Blob(csv += tempCsv);
                navigator.msSaveBlob(blobObject, filename + ".csv");
            } else {
                window.open(encodeURI(csv += tempCsv));
            }

        }   

This should also support IE with the msBlob but I haven't really tested it

deveshsinghal22 commented 7 years ago

@lylynguyen you can achieve this by adding exportFilename="yourFileName" in datatable

cagataycivici commented 7 years ago

This should be fixed in recent PrimeNG release, please try with them and if issue persists drop a comment and we'll reopen.

jespergothe commented 6 years ago

It took me a while to understand I could actually bind exportfilename to a property in my component. That way I can change it depending on choices made in the user interface. dynamicExportFileName is my own property and the value is generated from a class method/function.


<p-dataTable #dt tableStyleClass="ibox-content" [value]="fetchedDeliveries" [loading]="loading" [rows]="20" [rowsPerPageOptions]="[20,50,100]"
    [paginator]="true" [pageLinks]="3" [editable]="false" exportFilename="{{dynamicExportFileName}}">

I am on primeng-6.0.0-alpha