12/08/2021

Export table html to excel with utf-8 using javascript

 // đây là hàm export toàn bộ nội dung trong 1 bảng html ra excel

function exportTableToExcel(tableID, filename = '') {

        var downloadLink;

        var dataType = 'application/vnd.ms-excel;charset=utf-8';

        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();

        }

    }


//sử dụng

<button class="btn btn-success" onclick="exportTableToExcel('tableId', 'file_excel.xlsx')">Export</button>

Không có nhận xét nào:

Đăng nhận xét