简体   繁体   中英

How to export HTML data into Excel in correct format?

I am using jQuery to export HTML data into Excel. Data is exporting, but it's not exporting in a correct format. On opening the Excel file it says:

The file format and extension of "download.xls" don't match. The file could be corrupted or unsafe. Unless you trust its source, don't open it. Do you want to open it anyway?

And when I open it, the data there is present, but badly merged. What should I do?

echo "<div id=dvData3>";
//echo "<table border=5 cellpadding=5  cellspacing=0 style=border-collapse: collapse >";

echo "<table>";
echo "<tr>";
echo "<td width=14% align=center>Name</td>";
echo "<td width=14% align=center>Grand Total</td>";
echo "<td width=14% align=center>Expanse Type</td>";
echo "</tr>";

while($allrows=mysql_fetch_array($newresult1))
{

  $name=$allrows["empid"];
  $gamount=$allrows["gtotal"];
  $exptype=$allrows["expanseType"];

  echo "<tr>";
  echo "<td width=14% align=center>$name</td>";
  echo "<td width=14% align=center>$gamount</td>";
  echo "<td width=14% align=center>$exptype</td>";
  echo "</tr>";
}

echo "<tr>";
echo "<td width=14% align=center>Total Amount</td>";
echo "<td width=14% align=center>$Tamount</td>";

echo "</table>";
echo "</div>";

echo "<input type='button' id=\"btnExport3\" value=\" Export Table data into Excel \" />"; 

}

And here's my jQuery function:

<script>
  $(document).ready(function(){ 
    $("#btnExport3").click(function (e) {

      window.open('data:application/vnd.ms-excel,' + $('#dvData3').html());
      //window.open('data:application/csv,charset=utf-8,' +  $('#dvData').html());
      e.preventDefault(); 

    });
  }); 
</script>

Try this code:

$(document).ready(function() {
$("#btnExport3").click(function(e) {

    var a = document.createElement('a');
    //getting data from our div that contains the HTML table
    var data_type = 'data:application/vnd.ms-excel';
    var table_div = document.getElementById('dvData3');
    var table_html = table_div.outerHTML.replace(/ /g, '%20');
    a.href = data_type + ', ' + table_html;
    //setting the file name
    a.download = 'download.xlsx';
    //triggering the function
    a.click();
    //just in case, prevent default behaviour
    e.preventDefault();
});
});

如果您安装了最新的Office,请将.xls更改为.xlsx。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM