GarrettMurphy
GarrettMurphy

Reputation: 289

Open HTML page in Excel via Javascript

We have reports generated in HTML that our users frequently open in Excel, which we serve simple enough by using the content-type. However, we've recently had a wrinkle popup: some of these reports use a lot of Javascript to conduct dynamic grouping/sorting, and the user wants to download this "finished" version of the report into Excel. I have a functioning Javascript function for that:

var uri = 'data:application/vnd.ms-excel;base64,';
var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">';
template += '<head></head>';
template += '<body><table>{table}</table></body></html>';
var base64 = function(s) { 
    return window.btoa(unescape(encodeURIComponent(s)));
};
var format = function(s, c) { 
    return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; });
};
var ctx = {worksheet: name || 'Worksheet', table: daBody};
window.location.href = uri + base64(format(template, ctx));

I found that IE doesn't support window.btoa, so I addressed that, but now I get the following error when attempting to open the data in Excel:

The data area passed to a system call is too small.

I believe, despite the message, that this is caused by the base64 string in the URI being too long (I've seen in the past that IE doesn't accept extremely long URLs, and believe this is connected).

So, does anybody have any alternative method I can use for this in IE?

Upvotes: 2

Views: 3393

Answers (1)

GarrettMurphy
GarrettMurphy

Reputation: 289

Found a valid way of going about doing it:

  1. Used jQuery to create a form, gather all the HTML of the page (after Javascript completes) and post it to my server
  2. On my server, I created a function that takes in the form post and just returns it with the return type of "application/msexcel"
  3. Added script to run this Javascript on window.load of the report page

It's pretty hacky, but it works like a champ in all browsers

Upvotes: 2

Related Questions