2015-02-10 51 views
0

我有表并使用JS导出到Excel。 <table>标签有一些说明和类(<table class="someClassName" border="0" cellpadding="0" cellspacing="0">)导出到Excel - Chrome和Firefox中的问题

当它导出到Excel时,excel文件包含表标签和值(<table> <tr> <td>value</td><td>value</td>...</tr>),看起来像一团糟!但是,如果我删除<table>中的所有说明和类,则在导出到Excel时,它看起来很好(没有<table> <tr> <td>...标记)。

一个问题是如何使导出的Excel看起来很好,但不删除<table>中的描述和类?谢谢!

HTML

<div class="dvData"> 
    <table class="header_detail" border="0" cellpadding="0" cellspacing="0"> 
     <tr> 
      <th>Billing System</th> 
      <th>Market Code</th> 
      <th>Payment Amount</th> 
     </tr> 
     <tr> 
      <td>RED</td> 
      <td>222</td> 
      <td>$103.00</td> 
     </tr> 
     <tr> 
      <td>BLUE</td> 
      <td>111</td> 
      <td>$13.00</td> 
     </tr> 
     <tr> 
      <td>GREEN</td> 
      <td>555</td> 
      <td>$143.00</td> 
     </tr> 
    </table> 
    </div> 
<br /> 
<input type="button" value="Export" class="toExcelButton" data-target="dvData" /> 

JS

$(document).ready(
     function() 
     { 
      $(".toExcelButton").click(function(e) { 
      e.stopPropagation(); 
      var table = $("." + $(this).data('target')); 
      window.open('data:application/vnd.ms-excel,' + $(table).html()); 
      e.preventDefault(); 
      }); 
     } 
    ); 
+1

为什么不直接使用jQuery克隆表,请从克隆的属性,然后导出属性少表? – JDB 2015-02-10 17:41:06

+0

@ JDB,非常感谢!你可以请示例“从克隆中删除属性,然后导出无属性表”? – 2015-02-10 20:01:49

回答

0

你可以使用jQuery的cloneremoveAttr函数来解决这个问题。

var newTable = $('#exportme').clone(), 
 
    wrapper = $('<div>').append(newTable); 
 

 
// For each element within the table (including the table)... 
 
$.each($('*', wrapper), function(i, elem){ 
 
    
 
    // Build a list of all attribute names... 
 
    var attributeNames = []; 
 
    $.each(elem.attributes, function(i, att) { 
 
    attributeNames.push(att.nodeName); 
 
    }); 
 
    
 
    // Then remove them. 
 
    attributeNames.forEach(function(attName){ 
 
    $(elem).removeAttr(attName); 
 
    }) 
 
}); 
 

 
$('#result').text(wrapper.html()); 
 

 
// Your final table will have no attributes... 
 
console.log(newTable[0]); 
 
// But your original table will be untouched. 
 
console.log($('#exportme')[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<table id="exportme" class="foo" data-bar="baz" style="display:none;"> 
 
    <tr class="firstr0w"> 
 
    <td data-foobar="baz">But keep my data!</td> 
 
    </tr> 
 
</table> 
 
<div id="result"></div>

+0

非常感谢!我刚刚尝试过,它使用'

​​...'内部'
'克隆了一个新表格,并且在Excel中,它不会删除所有表格的标记。 – 2015-02-10 21:36:10

+0

@abcidd你有足够的工作。如果你想知道如何自己将代码集成到代码中,我认为它会帮助你成长为程序员。 – JDB 2015-02-10 22:56:05

0

你有没有考虑使用Excel .csv文件?
您可以将表项移动到一个字符串中,并用逗号分隔项目。希望这可以帮助。

+0

非常感谢!你能更清楚地知道如何将表格项目变成一个字符串,并用逗号分隔项目吗? – 2015-02-10 19:50:35