3

I am able to export an HTML table using jquery if the <table> does not have an ID or class:

http://jsfiddle.net/n9XRx/

But if my table has either an ID or a class attr the following jquery kicks out a string of html in one cell to excel:

$( "#clickExcel" ).click(function() {  
var dtltbl = $('#dtltbl').html();    
window.open('data:application/vnd.ms-excel,' + $('#dtltbl').html());
});

I can get around this by removing the tables classes and ID, but that's not ideal. Anybody have a solution?

Ryan
  • 804
  • 1
  • 11
  • 24
  • The whitespace is being removed so `` becomes ``. Also `This has a space` becomes `Thishasaspace`. I don't know how to fix it, just thought I would add. This is a pretty neat trick if you can get it working! – Malk Jan 24 '14 at 00:56
  • @Malk: Yeah, the same thing happens with the `` element, it turns into `` which screws it all up. I have success with removing the ID and Class attr. Worse case I can wrap the table in a div, store the existing class and ID before deleting them, export it, then use the wrapped div to find the table and add the save ID and Classes back in, but damn thats ugly.
    – Ryan Jan 24 '14 at 01:20
  • I think you need to encode your content: http://stackoverflow.com/questions/17142427/javascript-to-export-html-table-to-excel – Tim Williams Jan 24 '14 at 01:48

2 Answers2

1

I had the same problem as you and It has been solved this way:

$("#btnExport").click(function (e) {
    window.open('data:application/vnd.ms-excel,' +'<table>' +$("#YourTableId").html()+ '</table>');
    e.preventDefault();
});

Hope It Helps

Sapikelio
  • 2,594
  • 2
  • 16
  • 40
0

You can encodeURI the string before opening it.

$( "#clickExcel" ).click(function() {  
    var dtltbl = $('#dtltbl').html();    
    window.open('data:application/vnd.ms-excel,' + encodeURI($('#dtltbl').html()));
});