Link to home
Start Free TrialLog in
Avatar of Demosthenes
Demosthenes

asked on

jquery table to excel file

I have a html jqgrid table that I make into csv data.  I then want to write that csv to excel.   I believe the issue is in this line:
window.open('data:application/csv;charset=utf-8,' + encodeURIComponent(html));

Open in new window

It does some wacky stuff on people's PCs, I dont know why, I think it it because they do not have *.csv associated with anything maybe.  But, in C# I do other data and it works well.  Question is, assuming my csv data inside the html variable is good, how do I open it in Excel, and possibly with a friendlier filename.  It seems to make a wacky filename like "XXvZZr12HJ.csv.csv".  I would be fine with a static filename like "hello.csv".

In C# I would do this code, and it would open a nice Excel file:
     Response.Clear();
      Response.Buffer = true;
      Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.csv");
      Response.Charset = "";
      Response.ContentType = "application/text";
      Response.Output.Write(sb.ToString());
      Response.Flush();
      Response.End();

Open in new window

SOLUTION
Avatar of Rainer Jeschor
Rainer Jeschor
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Demosthenes
Demosthenes

ASKER

This seems to work, I found it right after I posted this q

        var uri = 'data:text/csv;charset=utf-8,' + html;
        var downloadLink = document.createElement("a");
        downloadLink.href = uri;
        downloadLink.download = "Export.csv";
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);

Open in new window

Hey guys this doesn't seem to work in IE.  Either solution.
IE specifically does not support this citing security reasons
https://msdn.microsoft.com/en-us/library/cc848897%28v=vs.85%29.aspx
For security reasons, data URIs are restricted to downloaded resources. Data URIs cannot be used for navigation, for scripting, or to populate frame or iframe elements.

The right way of doing this would be to send the data to the server and have the server send back the file. Either that or disqualify IE as a target browser.