Javascript/ jQuery : Exporting data in CSV not working in IE

后端 未结 6 1426
太阳男子
太阳男子 2020-12-25 13:43

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

6条回答
  •  隐瞒了意图╮
    2020-12-25 14:26

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

    1. Add the following iframe anywhere in your page:

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

    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:

    4. Add this to your JavaScript file or section:

    5. 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;
      };
      Name Age Email
      Andrew 20 andrew@me.com
      Bob 32 bob@me.com
      Sarah 19 sarah@me.com
      Anne 25 anne@me.com
      Click this to download a .csv

提交回复
热议问题