Monday, 20 July 2015

Export html table data to csv file using JavaScript

Recently i have posted Import CSV File Data Into Database Using PHP article this concept based import excel sheet data into database.Similar like i have posted this topic, here i am using JavaScript for converting html table data into excel (CSV) document. this concept best helpful for shopping cart, school management web sites. Just take a quick look this live demo.

export html data to csv

Html

<div align="center"  id="reportsummary">
    <table border="1">
      <tr>
        <td>No</td>
        <td>Username</td>
        <td>Email -ID</td>
        <td>Register date</td>
      </tr>
      <tr>
        <td>1</td>
        <td>karthick</td>
        <td>karthick@gmail.com</td>
        <td>01/01/2015</td>
      </tr>
      <tr>
        <td>2</td>
        <td>mostlikers</td>
        <td>mostlikers@gmail.com</td>
        <td>02/01/2015</td>
      </tr>
    </table>
  </div>
  <form action="exporttoexcel.php" class="exconvert"  method="post">
    <input type="hidden" id="expo1" name="expo1">
    <input type="submit" value="Download Excel" />
  </form>

Javascript
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>         
<script type="text/javascript">
$(document).ready(function(){
    $(document).on("submit", '.exconvert', function(event) {
        $("#expo1").val( $("<div>").append( $("#reportsummary").eq(0).clone() ).html() )
     });         
});
</script>

exporttoexcel.php
<?php
    header('Content-Type: application/force-download');
    header('Content-disposition: attachment; filename=report.xls');
    header("Pragma: ");
    header("Cache-Control: ");
    echo $_REQUEST['expo1'];
?>

0 comments:

Post a Comment