Javascript/ jQuery : Exporting data in CSV not working in IE
Asked Answered
M

6

20

I need to Export Data displayed in a Table to CSV Format. I have tried lot many things but couldn't get it working for IE 9 and above.

I have created a dummy fiddle with my code.

var data = [
    ["name1", "city1", "some other info"],
    ["name2", "city2", "more info"]
];//Some dummy data

var csv = ConvertToCSV(data);//Convert it to CSV format
var fileName = "test";//Name the file- which will be dynamic

if (navigator.userAgent.search("MSIE") >= 0) {
    //This peice of code is not working in IE, we will working on this
    //TODO
    var uriContent = "data:application/octet-stream;filename=" + fileName + '.csv' + "," + escape(csv);
    window.open(uriContent + fileName + '.csv');
} else {
    var uri = 'data:text/csv;charset=utf-8,' + escape(csv);
    var downloadLink = document.createElement("a");
    downloadLink.href = uri;
    downloadLink.download = fileName + ".csv";
    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
}

I have seen many of the links in Stackoverflow, but couldn't find anything that's working with IE9 or above. Like @ Terry Young explains in how-to-data-export-to-csv-using-jquery-or-javascript

Also, tried-

var csv = ConvertToCSV(_tempObj);
        var fileName = csvExportFileName();
        if (navigator.appName != 'Microsoft Internet Explorer') {
            window.open('data:text/csv;charset=utf-8,' + escape(str));
        }
        else {
            var popup = window.open('', 'csv', '');
            popup.document.body.innerHTML = '<pre>' + str + '</pre>';
        }

Not sure how to fix it. I don't want to hit the server and export my CSV (the requirement say so).

Morell answered 12/8, 2013 at 11:20 Comment(4)
@Morell did you resolve this at all - i am facing the same issue - i had a look at this workaround - blog.paxcel.net/blog/… but it hasnt worked for meShool
@Shool Nopes. I was not able to solve it . Finally I had to use Server Side logic to get the desired.Morell
ok thanks will have to keep looking for something what a nightmare!Shool
@inaamhusain the third one works for me.Subassembly
W
18

After using Javascript it will solve your problem.

Use this for IE,

var IEwindow = window.open();
IEwindow.document.write('sep=,\r\n' + CSV);
IEwindow.document.close();
IEwindow.document.execCommand('SaveAs', true, fileName + ".csv");
IEwindow.close();

For more information i have written tutorial on that, see - Download JSON data in CSV format Cross Browser Support

Hope this will be helpful for you.

Winer answered 10/2, 2015 at 14:16 Comment(5)
Is there anyway to specify a separator without actually inserting it into the CSV file itself? For some reason, when I generate CSVs in Chrome (using method similar to one in OP), Excel can open up the CSV just fine without the sep=, lineArmful
I have to support modern browsers and IE8. This bit of code has helped me tremendously. Thanks!Weary
Did not get a chance to implement ur code but as @GeoJacob and THarris said it works for them Marking your answer as Accepted. Thanks for you help & hope it helps others.Morell
Thank you very much for you solution. This helped me out. This solution can be used to export XLS (Excel) file as well. To export excel file, replace the line with "CSV" by a variable that contains the xml definition of the excel file and then replace the ".csv" extension by ".xls".Stencil
In IE11 (at least) the file extension is striped if a user attempts to rename the file. Note: in the download window '.csv' is not listed under 'file-name' and 'Save as type' is HTML file. Has anyone else encountered this / found a solution?Cannibalism
T
7

For IE 10+ you can do:

var a = document.createElement('a');
        if(window.navigator.msSaveOrOpenBlob){
            var fileData = str;
            blobObject = new Blob([str]);
            a.onclick=function(){
                window.navigator.msSaveOrOpenBlob(blobObject, 'MyFile.csv');
            }
        }
        a.appendChild(document.createTextNode('Click to Download'));
        document.body.appendChild(a);

I don't believe it to be possible in earlier versions of IE. Without invoking the activeX object, but if that's acceptable you could use:

var sfo=new ActiveXObject('scripting.FileSystemObject');
var fLoc=sfo.CreateTextFile('MyFile.csv');
fLoc.WriteLine(str);
fLoc.close();

Which would write the file directly to the user's file system. This will however generally prompt the user asking if they want to allow the script to run. The prompt can be disabled in an intranet environment.

Tai answered 25/6, 2014 at 20:9 Comment(0)
H
6

This is also one of the answers which I used and working great for IE 10+ versions :

var csv = JSON2CSV(json_obj);            
var blob = new Blob([csv],{type: "text/csv;charset=utf-8;"});

if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, "fileName.csv")
    } else {
        var link = document.createElement("a");
        if (link.download !== undefined) { // feature detection
            // Browsers that support HTML5 download attribute
            var url = URL.createObjectURL(blob);
            link.setAttribute("href", url);
            link.setAttribute("download", "fileName.csv");
            link.style = "visibility:hidden";
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }           
    }

Hope this helps.

Hyatt answered 6/10, 2015 at 10:55 Comment(0)
I
4

I got the solution for it which is supporting IE 8+ for me. We need to specify the separator as shown below.

if (navigator.appName == "Microsoft Internet Explorer") {    
    var oWin = window.open();
    oWin.document.write('sep=,\r\n' + CSV);
    oWin.document.close();
    oWin.document.execCommand('SaveAs', true, fileName + ".csv");
    oWin.close();
  }  

You can go through the link http://andrew-b.com/view/article/44

Ineluctable answered 12/11, 2014 at 12:39 Comment(1)
The link is deadStencil
B
1

This will work on any browser, without the need of jQuery.

  1. Add the following iframe anywhere in your page:

    <iframe id="CsvExpFrame" style="display: none"></iframe>

  2. Give an id to the table in the page you want to export:

    <table id="dataTable">

  3. Customize your link or button to call the ExportToCsv function, passing the default file name and the id of table as parameters. For example:

    <input type="button" onclick="ExportToCsv('DefaultFileName','dataTable')"/>

  4. Add this to your JavaScript file or section:

function ExportToCsv(fileName, tableName) {
  var data = GetCellValues(tableName);
  var csv = ConvertToCsv(data);
  if (navigator.userAgent.search("Trident") >= 0) {
    window.CsvExpFrame.document.open("text/html", "replace");
    window.CsvExpFrame.document.write(csv);
    window.CsvExpFrame.document.close();
    window.CsvExpFrame.focus();
    window.CsvExpFrame.document.execCommand('SaveAs', true, fileName + ".csv");
  } else {
    var uri = "data:text/csv;charset=utf-8," + escape(csv);
    var downloadLink = document.createElement("a");
    downloadLink.href = uri;
    downloadLink.download = fileName + ".csv";
    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
  }
};

function GetCellValues(tableName) {
  var table = document.getElementById(tableName);
  var tableArray = [];
  for (var r = 0, n = table.rows.length; r < n; r++) {
    tableArray[r] = [];
    for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
      var text = table.rows[r].cells[c].textContent || table.rows[r].cells[c].innerText;
      tableArray[r][c] = text.trim();
    }
  }
  return tableArray;
}

function ConvertToCsv(objArray) {
  var array = typeof objArray != "object" ? JSON.parse(objArray) : objArray;
  var str = "sep=,\r\n";
  var line = "";
  var index;
  var value;
  for (var i = 0; i < array.length; i++) {
    line = "";
    var array1 = array[i];
    for (index in array1) {
      if (array1.hasOwnProperty(index)) {
        value = array1[index] + "";
        line += "\"" + value.replace(/"/g, "\"\"") + "\",";
      }
    }
    line = line.slice(0, -1);
    str += line + "\r\n";
  }
  return str;
};
<table id="dataTable">
  <tr>
    <th>Name</th>
    <th>Age</th>
    <th>Email</th>
  </tr>
  <tr>
    <td>Andrew</td>
    <td>20</td>
    <td>[email protected]</td>
  </tr>
  <tr>
    <td>Bob</td>
    <td>32</td>
    <td>[email protected]</td>
  </tr>
  <tr>
    <td>Sarah</td>
    <td>19</td>
    <td>[email protected]</td>
  </tr>
  <tr>
    <td>Anne</td>
    <td>25</td>
    <td>[email protected]</td>
  </tr>
</table>

<a href="#" onclick="ExportToCsv('DefaultFileName', 'dataTable');return true;">Click this to download a .csv</a>
Bedim answered 17/4, 2015 at 11:31 Comment(0)
F
0

use Blob object Create a blob object and use msSaveBlob or msSaveOrOpenBlob The code is working in IE11 (not tested for other browsers)

    <script>


 var csvString ='csv,object,file';
    var blobObject = new Blob(csvString); 

        window.navigator.msSaveBlob(blobObject, 'msSaveBlob_testFile.txt'); // The user only has the option of clicking the Save button.
        alert('note the single "Save" button below.');

        var fileData = ["Data to be written in file."];
    //csv string object inside "[]"
        blobObject = new Blob(fileData);
        window.navigator.msSaveOrOpenBlob(blobObject, 'msSaveBlobOrOpenBlob_testFile.txt'); // Now the user will have the option of clicking the Save button and the Open button.`enter code here`
        alert('File save request made using msSaveOrOpenBlob() - note the two "Open" and "Save" buttons below.');
      </script>
Frivolity answered 3/9, 2016 at 14:59 Comment(1)
Thank You so much. This solution worked for me on IE11.Countryside

© 2022 - 2024 — McMap. All rights reserved.