2016-01-22 3 views
2

Я изучал некоторые плагины jQuery, которые могут это сделать. Я решил использовать его в http://www.jqueryscript.net/table/Export-Html-Table-To-Excel-Spreadsheet-using-jQuery-table2excel.html, и я следовал его инструкциям как можно ближе. Я тестировал этот плагин, но каждый раз, когда я нажимаю кнопку для экспорта, ничего не происходит. Таблица заполняется с использованием PHP (который вытаскивает данные с сервера MySQL), и следующий сценарий, который я сейчас имею в наличии.Экспорт таблицы HTML в файл Excel

<script> 
     $(document).ready(function() { 

       //activate footable jquery plugin (this is the dynamic table on the report page with search and sorting functions) 
       $('.footable').footable(); 


     }); 

     //Prepare table2excel plugin (clicking the export button will send the main table to an Excel spreadsheet) 
     $("button").click(function(){ 
      $(".footable").table2excel({ 
       //Exclude CSS class specific to this plugin 
       exclude: ".noExl", 
       name: "Excel Document Name" 
      }); 
     }); 

</script> 

footable дисплей не изменился после того, как я добавил новый код. Что я могу сделать? Я продолжаю думать, что я просто потерял блок table2excel, но даже когда у меня было это в блоке ready(function(){}), ничего не произошло.

+0

Имеет ли в консоли браузера отображаются любые ошибки ? – Xufox

+0

Нет, ничего. – user3521737

+0

он определенно находится за пределами готового блока, когда он, вероятно, будет внутри него. Поместите предупреждение или консольный журнал в обработчик кликов, чтобы убедиться, что он даже стреляет – charlietfl

ответ

0

удалось это исправить. Первоначально я подозревал, что проблема не в том, что он не включен в готовые функции, и подумал, что это исправит проблему, но это только часть проблемы. Я тоже забыл запятую. Конечный результат следующий.

<script> 
    $(document).ready(function() { 

     //activate footable jquery plugin (this is the dynamic table on the report page with search and sorting functions) 
     $('.footable').footable(); 

     //Prepare table2excel plugin (clicking the export button will send the main table to an Excel spreadsheet) 
     $("button.excelexport").click(function(){ 
      $("#footable").table2excel({ 
       //Exclude CSS class specific to this plugin 
       exclude: ".noExl", 
       name: "Merchandising Report", 
       filename: "merchReportTable" 
      }); 
     }); 

    });    

</script> 
1

Как @charlietfl сказал, что вам нужно связать .click() внутри $(document).ready, потому что если элемент не существует, когда вы пытаетесь его связать.

И таким образом вам не нужно использовать плагин

function exportGrid(gridID,filename) { 
    var html = $('#' + gridID).html(); 
    var a = document.createElement('a'); 
    a.id = 'tempLink'; 
    a.href = 'data:application/vnd.ms-excel,' + html; 
    a.download = filename + ".xls"; 
    document.body.appendChild(a); 
    a.click(); // Downloads the excel document 
    document.getElementById('tempLink').remove(); 
} 
$(document).ready(function() { 
    $("button").click(function(){ 
     exportGrid("TheGridId","The excel name"); 
    }); 
}); 

Здесь у вас есть пример https://jsfiddle.net/0mzn7uLq/

+0

Этот метод используется только для браузеров Firefox и Chrome? Я попробовал его в IE9, он не работает, он показывает, что «веб-страница не может быть отображена» при нажатии кнопки. Не могли бы вы помочь? – Disera

0

Это код, который вы можете использовать для экспорта HTML таблицы, чтобы преуспеть файл с именем пользовательского файла. Я пробовал IE11, Firefox 48 & chrome 51.

  1. Добавить <iframe id="txtArea1" style="display:none"></iframe> в HTML части.
  2. Добавить кнопку <button id="btnExport" onclick="toExcel_()">Export to excel</button>, которая вызовет функцию «toExcel_()».

Ps: Я новичок в Stackoverflow, поэтому, пожалуйста, простите мой формат ответа: D

function toExcel_(){ 
    var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>"; 
    var textRange; var j=0; 
    tab = document.getElementById('tblExport'); // 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>"; 


     var ua = window.navigator.userAgent; 
     var msie = ua.indexOf("MSIE"); 
     var dt = new Date(); 
     var day = dt.getDate(); 
     var month = dt.getMonth() + 1; 
     var year = dt.getFullYear(); 
     var hour = dt.getHours(); 
     var mins = dt.getMinutes(); 
     var postfix = day + "." + month + "." + year + "_" + hour + "." + mins; 


    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,"Report.xls"); 
    } 
    else // For Chrome and firefox (Other broswers not tested) 
    { 

     uriContent = "data:application/vnd.ms-excel," + encodeURIComponent(tab_text); 


     var sa = document.createElement("a"); 
     sa.setAttribute("href", uriContent); 
     sa.setAttribute("download", "Report"+postfix +".xls"); 
     document.body.appendChild(sa); // Required for FF 

     sa.click(); 
    } 


    return (sa); 

}

0

<html> 
 

 
<head> 
 
    <script src="jquery.min.js"></script> 
 
    <script src="jquery.btechco.excelexport.js"></script> 
 
    <script src="jquery.base64.js"></script> 
 

 
    <script> 
 
    $(document).ready(function() { 
 
     $("#btnExport").click(function() { 
 
     $("#tblExport1").btechco_excelexport({ 
 
      containerid: "tblExport1", 
 
      datatype: $datatype.Table 
 
     }); 
 
     }); 
 
    }); 
 
    </script> 
 
</head> 
 

 
<body> 
 

 
    <div id="dvd"> 
 
    <table id="tblExport1" style="border:1px solid black; "> 
 
     <thead> 
 
     <tr> 
 
      <th>#</th> 
 
      <th>First Name</th> 
 
      <th>Last Name</th> 
 
      <th>Username</th> 
 
     </tr> 
 
     </thead> 
 
     <tbody> 
 
     <tr> 
 
      <td style='background-color:red;'>1</td> 
 
      <td>Mark</td> 
 
      <td>Otto</td> 
 
      <td>@mdo</td> 
 
     </tr> 
 
     <tr> 
 
      <td>2</td> 
 
      <td>Jacob</td> 
 
      <td>Thornton</td> 
 
      <td>@fat</td> 
 
     </tr> 
 
     <tr> 
 
      <td>3</td> 
 
      <td>Larry</td> 
 
      <td>the Bird</td> 
 
      <td>@twitter</td> 
 
     </tr> 
 
     <tr> 
 
      <td>4</td> 
 
      <td>Larry</td> 
 
      <td>the Bird</td> 
 
      <td>@twitter</td> 
 
     </tr> 
 
     </tbody> 
 
    </table> 
 
    </div> 
 
    <div> 
 
    <button id="btnExport">Export to excel</button> 
 
    </div> 
 
</body> 
 

 
</html>

+0

, пожалуйста, добавьте некоторые пояснения к этому коду? –

Смежные вопросы