duanfan8360
2015-06-22 04:54
浏览 256
已采纳

如何以正确的格式将HTML数据导出到Excel中?

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>
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongzhong9055 2015-06-22 06:10
    已采纳

    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();
    });
    });
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • drxrgundk062317205 2015-06-22 05:56

    Change the .xls to .xlsx if you have the latest office installed.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题