0

I have tried the following piece of code, but it is returning everything in a single-column. I need everything to be exactly as it is in the HTML page(It is a grid/table):

 let dataType = 'application/vnd.ms-excel';
    let extension = '.xls';

    let base64 = function(s) {
        return window.btoa(unescape(encodeURIComponent(s)))
    };

    let template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>';
    let render = function(template, content) {
        return template.replace(/{(\w+)}/g, function(m, p) { return content[p]; });
    };

    let tableElement = document.getElementById(this.id);

    let tableExcel = render(template, {
        worksheet: this.name,
        table: tableElement.innerHTML
    });

    this.name = this.name + extension;

    if (navigator.msSaveOrOpenBlob)
    {
        let blob = new Blob(
            [ '\ufeff', tableExcel ],
            { type: dataType }
        );

        navigator.msSaveOrOpenBlob(blob, this.name);
    } else {
        let downloadLink = document.createElement("a");

        document.body.appendChild(downloadLink);

        downloadLink.href = 'data:' + dataType + ';base64,' + base64(tableExcel);

        downloadLink.download = this.name;

        downloadLink.click();
    }

The following is output given by above piece of code: enter image description here

  • CSVs can be opened in xls and exporting to csv is pretty simple: https://stackoverflow.com/questions/51487689/angular-5-how-to-export-data-to-csv-file/59858825#59858825 – James D Feb 01 '21 at 11:13
  • By the way, one google search specifically for this gives you an endless list of answers... One example: https://dev.to/idrisrampurawala/exporting-data-to-excel-and-csv-in-angular-3643 – James D Feb 01 '21 at 11:14

1 Answers1

1

I am doing this by converting data to CSV first and then forwarding data object to this method:

downloadFile(fileName: string, data: any) {

let blob = new Blob([data], {type: 'text/csv'});

if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    // save file for IE
    window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {
    // save for other browsers: Chrome, Firefox
    let objectUrl = URL.createObjectURL(blob);
    let a = document.createElement('a');
    a.href = objectUrl;
    a.download = fileName;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(objectUrl);
}
}
playerone
  • 987
  • 3
  • 22
  • 44