我有表,并使用JS导出到Excel。<table>标记有一些描述和类(<table class="someClassName" border="0" cellpadding="0" cellspacing="0">)。
当它导出到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();
});
}
);发布于 2015-02-10 21:01:07
您可以使用jQuery的无性系和removeAttr函数来解决这个问题。
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>
发布于 2015-02-10 18:22:01
您考虑过使用excel .CSV文件吗?
您可以将表项移动到由逗号分隔的字符串中。希望这能有所帮助。
https://stackoverflow.com/questions/28438041
复制相似问题