Menus

Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Sunday 18 August 2019

Export HTML table to excel



       This is simple example for data export to excel from PHP or HTML file using java script. It is very useful for web application developers.

Let's try this

Create studentlist.php or studentlist.html file


<html>
<head>
<title>Export to excel</title>

<Script>

function exportExcel(){

    var tableID = "studentslist";
    var filename = "student_list.xls";

    var downloadLink;
    var dataType = 'application/vnd.ms-excel';
    var tableSelect = document.getElementById(tableID);
    var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
    
    
    // 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();
    }
}

</Script>

</head>

<body>

<table id="studentslist" width="750" border="1">

<tr><td colspan="2" align="center">Student List</td></tr>

<tr>
<td>SL No</td>
<td>Name</td>
</tr>

<tr>
<td>1</td>
<td>Sahneesh</td>
</tr>

<tr>
<td>2</td>
<td>Aneesh</td>
</tr>

</table>

<button onclick="exportExcel()">Export To Excel File</button>

</body>
</html>