web-dev-qa-db-fra.com

L'exportation des données de tableau html vers Excel à l'aide de JavaScript / JQuery ne fonctionne pas correctement dans le navigateur chrome

J'ai un tableau HTML dans le modèle de vélocité. Je souhaite exporter les données de la table html vers Excel à l'aide de Java script ou de jquery, fourni avec tous les navigateurs. J'utilise le script ci-dessous

<script type="text/javascript">
function ExportToExcel(mytblId){
       var htmltable= document.getElementById('my-table-id');
       var html = htmltable.outerHTML;
       window.open('data:application/vnd.ms-Excel,' + encodeURIComponent(html));
    }
</script>

Ce script fonctionne très bien dans Mozilla Firefox , il s’affiche avec une boîte de dialogue Excel et demande des options d’ouverture ou de sauvegarde. Mais lorsque j'ai testé le même script dans navigateur Chrome, il ne fonctionnait pas comme prévu. Lorsque l'utilisateur clique sur ce bouton, aucune fenêtre contextuelle d'Excel ne s'affiche. Les données sont téléchargées dans un fichier avec "type de fichier: fichier", sans extension comme . Xls Il n'y a pas d'erreur dans chrome console .

Exemple Jsfiddle:

http://jsfiddle.net/insin/cmewv/

Cela fonctionne très bien dans Mozilla mais pas en chrome.

Cas de test du navigateur Chrome:

Première image: je clique sur le bouton Exporter vers Excel

First Image:I click on Export to Excel button

et résultat:

Result

80
Sukane

Le script d'exportation Excel fonctionne sur IE7 +, Firefox et Chrome.

function fnExcelReport()
{
    var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
    var textRange; var j=0;
    tab = document.getElementById('headerTable'); // id of table

    for(j = 0 ; j < tab.rows.length ; j++) 
    {     
        tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
        //tab_text=tab_text+"</tr>";
    }

    tab_text=tab_text+"</table>";
    tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
    tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
    tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE "); 

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer
    {
        txtArea1.document.open("txt/html","replace");
        txtArea1.document.write(tab_text);
        txtArea1.document.close();
        txtArea1.focus(); 
        sa=txtArea1.document.execCommand("SaveAs",true,"Say Thanks to Sumit.xls");
    }  
    else                 //other browser not tested on IE 11
        sa = window.open('data:application/vnd.ms-Excel,' + encodeURIComponent(tab_text));  

    return (sa);
}

Il suffit de créer un iframe vierge:

<iframe id="txtArea1" style="display:none"></iframe>

Appelez cette fonction sur:

<button id="btnExport" onclick="fnExcelReport();"> EXPORT </button>
138
sampopes

Le plugin Datatable résout le mieux le problème et nous permet d'exporter les données du tableau HTML dans Excel, PDF, TEXT. facilement configurable.

Veuillez trouver l'exemple complet dans le lien de référence datatable ci-dessous:

https://datatables.net/extensions/buttons/examples/html5/simple.html

(capture d'écran du site de référence datatable) enter image description here

31
Aditya

Cela pourrait aider

function exportToExcel(){
var htmls = "";
            var uri = 'data:application/vnd.ms-Excel;base64,';
            var 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>'; 
            var base64 = function(s) {
                return window.btoa(unescape(encodeURIComponent(s)))
            };

            var format = function(s, c) {
                return s.replace(/{(\w+)}/g, function(m, p) {
                    return c[p];
                })
            };

            htmls = "YOUR HTML AS TABLE"

            var ctx = {
                worksheet : 'Worksheet',
                table : htmls
            }


            var link = document.createElement("a");
            link.download = "export.xls";
            link.href = uri + base64(format(template, ctx));
            link.click();
}
24
todotresde

http://wsnippets.com/export-html-table-data-Excel-sheet-using-jquery/ essayez ce lien, cela pourrait résoudre votre problème

enter image description here

9
Uchit Shrestha

TableExport

TableExport - La bibliothèque simple et facile à implémenter pour exporter des tableaux HTML vers des fichiers xlsx, xls, csv et txt.

Pour utiliser cette bibliothèque, appelez simplement le constructeur TableExport :

new TableExport(document.getElementsByTagName("table"));

// OR simply

TableExport(document.getElementsByTagName("table"));

// OR using jQuery

$("table").tableExport(); 

Des propriétés supplémentaires peuvent être transmises pour personnaliser l'apparence de vos tableaux, boutons et données exportées. Voir ici plus d'infos

6
insign

Vous pouvez utiliser une bibliothèque comme ShieldUI pour le faire.

Il prend en charge l'exportation à la fois vers les formats Excel largement utilisés, XML et XLSX.

Plus de détails ici: http://demos.shieldui.com/web/grid-general/export-to-Excel

4
Vladimir Georgiev

En ce qui concerne les sampopes, répondez-vous du 6 juin 2014 à 11h59:

J'ai insérer un style CSS avec une taille de police de 20px pour afficher les données Excel plus grande. Dans les codes de sampopes, les balises <tr> principales sont manquantes. Par conséquent, j’envoie d’abord le titre et les lignes des autres tableaux d’une boucle.

function fnExcelReport()
{
    var tab_text = '<table border="1px" style="font-size:20px" ">';
    var textRange; 
    var j = 0;
    var tab = document.getElementById('DataTableId'); // id of table
    var lines = tab.rows.length;

    // the first headline of the table
    if (lines > 0) {
        tab_text = tab_text + '<tr bgcolor="#DFDFDF">' + tab.rows[0].innerHTML + '</tr>';
    }

    // table data lines, loop starting from 1
    for (j = 1 ; j < lines; j++) {     
        tab_text = tab_text + "<tr>" + tab.rows[j].innerHTML + "</tr>";
    }

    tab_text = tab_text + "</table>";
    tab_text = tab_text.replace(/<A[^>]*>|<\/A>/g, "");             //remove if u want links in your table
    tab_text = tab_text.replace(/<img[^>]*>/gi,"");                 // remove if u want images in your table
    tab_text = tab_text.replace(/<input[^>]*>|<\/input>/gi, "");    // reomves input params
    // console.log(tab_text); // aktivate so see the result (press F12 in browser)

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE "); 

     // if Internet Explorer
    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
        txtArea1.document.open("txt/html","replace");
        txtArea1.document.write(tab_text);
        txtArea1.document.close();
        txtArea1.focus(); 
        sa = txtArea1.document.execCommand("SaveAs", true, "DataTableExport.xls");
    }  
    else // other browser not tested on IE 11
        sa = window.open('data:application/vnd.ms-Excel,' + encodeURIComponent(tab_text));  

    return (sa);
}   
4
Bettelbursche
 function exportToExcel() {
        var tab_text = "<tr bgcolor='#87AFC6'>";
        var textRange; var j = 0, rows = '';
        tab = document.getElementById('student-detail');
        tab_text = tab_text + tab.rows[0].innerHTML + "</tr>";
        var tableData = $('#student-detail').DataTable().rows().data();
        for (var i = 0; i < tableData.length; i++) {
            rows += '<tr>'
                + '<td>' + tableData[i].value1 + '</td>'
                + '<td>' + tableData[i].value2 + '</td>'
                + '<td>' + tableData[i].value3 + '</td>'
                + '<td>' + tableData[i].value4 + '</td>'
                + '<td>' + tableData[i].value5 + '</td>'
                + '<td>' + tableData[i].value6 + '</td>'
                + '<td>' + tableData[i].value7 + '</td>'
                + '<td>' +  tableData[i].value8 + '</td>'
                + '<td>' + tableData[i].value9 + '</td>'
                + '<td>' + tableData[i].value10 + '</td>'
                + '</tr>';
        }
        tab_text += rows;
        var data_type = 'data:application/vnd.ms-Excel;base64,',
            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 border="2px">{table}</table></body></html>',
            base64 = function (s) {
                return window.btoa(unescape(encodeURIComponent(s)))
            },
            format = function (s, c) {
                return s.replace(/{(\w+)}/g, function (m, p) {
                    return c[p];
                })
            }

        var ctx = {
            worksheet: "Sheet 1" || 'Worksheet',
            table: tab_text
        }
        document.getElementById("dlink").href = data_type + base64(format(template, ctx));
        document.getElementById("dlink").download = "StudentDetails.xls";
        document.getElementById("dlink").traget = "_blank";
        document.getElementById("dlink").click();
    }

Ici, les valeurs 1 à 10 sont les noms de colonnes que vous obtenez

2
Rock

Au lieu d'utiliser window.open, vous pouvez utiliser un lien avec l'événement onclick.
Et vous pouvez mettre la table html dans l'URI et définir le nom du fichier à télécharger.

Démo en direct:

function exportF(elem) {
  var table = document.getElementById("table");
  var html = table.outerHTML;
  var url = 'data:application/vnd.ms-Excel,' + escape(html); // Set your html table into url 
  elem.setAttribute("href", url);
  elem.setAttribute("download", "export.xls"); // Choose the file name
  return false;
}
<table id="table" border="1">
  <tr>
    <td>
      Foo
    </td>
    <td>
      Bar
    </td>
  </tr>
</table>

<a id="downloadLink" onclick="exportF(this)">Export to Excel</a>
2
R3tep

Ma version de @sampopes répond

function exportToExcel(that, id, hasHeader, removeLinks, removeImages, removeInputParams) {
if (that == null || typeof that === 'undefined') {
    console.log('Sender is required');
    return false;
}

if (!(that instanceof HTMLAnchorElement)) {
    console.log('Sender must be an anchor element');
    return false;
}

if (id == null || typeof id === 'undefined') {
    console.log('Table id is required');
    return false;
}
if (hasHeader == null || typeof hasHeader === 'undefined') {
    hasHeader = true;
}
if (removeLinks == null || typeof removeLinks === 'undefined') {
    removeLinks = true;
}
if (removeImages == null || typeof removeImages === 'undefined') {
    removeImages = false;
}
if (removeInputParams == null || typeof removeInputParams === 'undefined') {
    removeInputParams = true;
}

var tab_text = "<table border='2px'>";
var textRange;

tab = $(id).get(0);

if (tab == null || typeof tab === 'undefined') {
    console.log('Table not found');
    return;
}

var j = 0;

if (hasHeader && tab.rows.length > 0) {
    var row = tab.rows[0];
    tab_text += "<tr bgcolor='#87AFC6'>";
    for (var l = 0; l < row.cells.length; l++) {
        if ($(tab.rows[0].cells[l]).is(':visible')) {//export visible cols only
            tab_text += "<td>" + row.cells[l].innerHTML + "</td>";
        }
    }
    tab_text += "</tr>";
    j++;
}

for (; j < tab.rows.length; j++) {
    var row = tab.rows[j];
    tab_text += "<tr>";
    for (var l = 0; l < row.cells.length; l++) {
        if ($(tab.rows[j].cells[l]).is(':visible')) {//export visible cols only
            tab_text += "<td>" + row.cells[l].innerHTML + "</td>";
        }
    }
    tab_text += "</tr>";
}

tab_text = tab_text + "</table>";
if (removeLinks)
    tab_text = tab_text.replace(/<A[^>]*>|<\/A>/g, "");
if (removeImages)
    tab_text = tab_text.replace(/<img[^>]*>/gi, ""); 
if (removeInputParams)
    tab_text = tab_text.replace(/<input[^>]*>|<\/input>/gi, "");

var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");

if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer
{
    myIframe.document.open("txt/html", "replace");
    myIframe.document.write(tab_text);
    myIframe.document.close();
    myIframe.focus();
    sa = myIframe.document.execCommand("SaveAs", true, document.title + ".xls");
    return true;
}
else {
    //other browser tested on IE 11
    var result = "data:application/vnd.ms-Excel," + encodeURIComponent(tab_text);
    that.href = result;
    that.download = document.title + ".xls";
    return true;
}
}

Nécessite un iframe

<iframe id="myIframe" style="opacity: 0; width: 100%; height: 0px;" seamless="seamless"></iframe>

Usage

$("#btnExportToExcel").click(function () {
    exportToExcel(this, '#mytable');
});
0
irfandar