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

How to export HTML data into Excel in correct format?

本文关键字:格式 Excel HTML 数据      更新时间:2023-09-26

我正在使用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>

试试这个代码:

$(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。