mollieda
mollieda

Reputation: 79

Download HTML table to Excel by using Javascript

In my Flask application, I created a button to extract the content of an HTML table into an Excel file. I used Javascript to extract from my interface the content of my HTML table in Excel format.

Unfortunately, when I run the code below, the downloaded Excel file is empty. Could you please help to correct my code below. Thanks.

function exportTableToExcel(filename = ''){
let downloadLink;
let dataType = 'application/vnd.ms-excel';
let tableSelect = document.getElementsByTagName("table");
let tableHTML = tableSelect[0].outerHTML.replace(/ /g, '%20');

// Specify file name
filename = 'All_Issues.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();
}
}

Upvotes: 1

Views: 1090

Answers (1)

tomasantunes
tomasantunes

Reputation: 945

The getElementsByTagName() function returns an array so you have to get the first element.

let tableHTML = tableSelect[0].outerHTML.replace(/ /g, '%20');

Upvotes: 1

Related Questions