0

I need to create an html script that create a table of contact and using the jQuery. I am trying to download this html page and convert it to excel file.

can anyone help me ??

I have this html file

contact.html

<div id="dv">
  <table id="tblExport" 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>
    </tbody>
  </table>
</div>
<div>
  <button id="btnExport">Export to excel</button>
</div>

</div>

So how to use jQuery to make the button download this table and convert it to an excel sheet ??

Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100

3 Answers3

0

Use the data:application property:

$("#Export").click(function (e) {
    window.open('data:application/vnd.ms-excel,' + $('#dv').html());
    e.preventDefault();
});

Open the downloaded file with Excel.

http://jsfiddle.net/eozwh49u/

Edward
  • 3,061
  • 6
  • 32
  • 52
0

You should use jquery on event over the click. Because if you are loading your form via ajax then click will not work. Then you can use simple html function on your div to get the html content and pass it to excel

$("body").on("click", "#btnExport", function () {
    window.open('data:application/vnd.ms-excel,' + $('#dv').html());
});
Avinash Jain
  • 7,200
  • 2
  • 26
  • 40
0

Simply put a click handler on the button and then export the div

$("#btnExport").on("click", function() {
    window.open('data:application/vnd.ms-excel,' + $('#dv').html());
});

NOW IF you want, you can trigger this from code:

$("#btnExport").trigger('click');
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100