export to excel using javascript

2019-08-07 08:23发布

问题:

I want to use javascript, to export the html table to excel. I used below script. Its working fine. Since few cells have special characters, I have escaped them. However, rows and contents after this special characters cell are not downloading. Please help. Here is the code:

<script type="text/javascript">
            $(document).ready(function(){      
    $("#exportToExcel").click(function() {  
        var data='<table border="1" class="csstable">'+$("#myTable").html().replace(/^[a-zA-Z!”$%&’()*\+,\/;\[\\\]\^_`{|}~<>]+$/gi, '')+'</table>';
                $('body').prepend("<form method='post' action='exporttoexcel.php' style='display:none' id='ReportTableData'><input type='text' name='tableData' value='"+data+"' ></form>");
         $('#ReportTableData').submit().remove();
         return false;
    });

});
</script>



<?php  
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename=".date('d-m-Y').'-'.date("H:i:s").'-'."myfile.xls");
header("Content-Transfer-Encoding: binary ");

echo strip_tags($_POST['tableData'],'<table><th><tr><td>');  
?>

回答1:

Think this is what you want: http://jsfiddle.net/9zaH7/

  1. takes table html, wraps in new table - this part seems not to be needed, but maybe you need to remove the styling/class?

  2. escapes the complete table to the form text field.

    $(document).ready(function(){
    $("#exportToExcel").click(function() {

        var data='<table border="1" class="csstable">'+$("#myTable").html()+'</table>';
        data=escape(data);
                $('body').prepend("<form method='post' action='exporttoexcel.php' style='display:block' id='ReportTableData'><input type='text' name='tableData' value='"+data+"'></form>");
    
         return false;
    });});