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

时间:2015-06-22 04:54:21

标签: javascript php jquery html excel

我正在使用jQuery将HTML数据导出到Excel中。数据正在导出,但它没有以正确的格式导出。在打开Excel文件时,它说:

  

" download.xls"的文件格式和扩展名不匹配。该文件可能已损坏或不安全。除非你相信它的来源,否则不要打开它。你想打开吗?

当我打开它时,那里的数据存在,但很难合并。我该怎么办?

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 \" />"; 

}

这是我的jQuery功能:

<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 个答案:

答案 0 :(得分:0)

试试这段代码:

$(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();
});
});

答案 1 :(得分:-2)

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