free-jqgrid / jqGrid

jQuery grid plugin
https://github.com/free-jqgrid/jqGrid
Other
478 stars 196 forks source link

How do you export JQGrid data with formatter in excel file? #497

Open teemer22 opened 4 years ago

teemer22 commented 4 years ago

I have tried the codes below but the header is not included in the excel file.

function tableToExcel(table, name, filename) { let uri = 'data:application/vnd.ms-excel;base64,', template = '

{table}
', base64 = function (s) { return window.btoa(decodeURIComponent(encodeURIComponent(s))) }, format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) }

if (!table.nodeType) table = document.getElementById(table)
var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }

var link = document.createElement('a');
link.download = filename;
link.href = uri + base64(format(template, ctx));
link.click();

}

function exportTableToExcel(tableID, filename) { var downloadLink; var dataType = 'application/vnd.ms-excel'; var tableSelect = document.getElementById(tableID); var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');

// Specify file name
filename = filename ? filename + '.xls' : 'excel_data.xls';

// Create download link element
downloadLink = document.createElement("a");

document.body.appendChild(downloadLink);

if (navigator.msSaveOrOpenBlob) {
    var blob = new Blob(['\ufeff', tableHTML], {
        type: dataType
    });
    navigator.msSaveOrOpenBlob(blob, filename);
} else {
    // Create a link to the file
    downloadLink.href = 'data:' + dataType + ', ' + tableHTML;

    // Setting the file name
    downloadLink.download = filename;

    //triggering the function
    downloadLink.click();
}

}