HTML表导出到Excel(XLS或CSV)

时间:2014-03-04 11:32:10

标签: javascript html excel xlsx

我正在尝试将HTML表格内容导出为ex​​cel。我看到this solution有效但不符合我的预期(因为 我无法选择要复制的列 ,而 不会适用于大表 )。

另一种解决方案是通过js复制并手动粘贴到excel文件,这样做效果不好,我真的不喜欢这种方法。

我想要的是,导出表的自定义视图,而不是所有列。向您展示我的意思的一个例子:

以下是常规表格视图:

enter image description here

以下是我想要在excel中展示的内容:

enter image description here

但是因为我有隐藏的字段,所以第一种方法不起作用:

enter image description here

我想要一个客户端,跨浏览器,解决方法/解决方案,考虑到我在表中有大约2,500行。

2 个答案:

答案 0 :(得分:1)

我做了一些非常相似的事情,每天在我的办公室使用它,按照网上的教程。 您可以将this template用于PHP:

<?
   $filename="sheet.xls";
   header ("Content-Type: application/vnd.ms-excel");
   header ("Content-Disposition: inline; filename=$filename");
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang=it><head>
<title>Titolo</title></head>
<body>
<table border="1">
<?
for ($i=1;$i < 11; $i++)
{
   echo "<tr>";
   for ($j=1; $j<11;$j++)
   {
      $a = $i * $j;
      echo "<td>$a</td>";
   }
   echo "</tr>";
}
?>
</table>
</body></html>

你可以用JS编写类似的东西,只需生成一个带有HTML标签的简单表格,并确保在标题中写出正确的代码。

答案 1 :(得分:1)

Excel Export Script works on IE7+ , Firefox and Chrome
===========================================================



function fnExcelReport()
    {
             var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
             var textRange; var j=0;
          tab = document.getElementById('headerTable'); // id of table


          for(j = 0 ; j < tab.rows.length ; j++) 
          {     
                tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
                //tab_text=tab_text+"</tr>";
          }

          tab_text=tab_text+"</table>";
          tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
          tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
                      tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params

               var ua = window.navigator.userAgent;
              var msie = ua.indexOf("MSIE "); 

                 if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer
                    {
                           txtArea1.document.open("txt/html","replace");
                           txtArea1.document.write(tab_text);
                           txtArea1.document.close();
                           txtArea1.focus(); 
                            sa=txtArea1.document.execCommand("SaveAs",true,"Say Thanks to Sumit.xls");
                          }  
                  else                 //other browser not tested on IE 11
                      sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  


                      return (sa);
                            }

    Just Create a blank iframe

        <iframe id="txtArea1" style="display:none"></iframe>

    Call this function on

        <button id="btnExport" onclick="fnExcelReport();"> EXPORT 
        </button>
相关问题