20

我需要将表格中显示的数据导出为 CSV 格式。我已经尝试了很多东西,但无法让它适用于 IE 9 及更高版本。

我用我的代码创建了一个虚拟小提琴。

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);
}

我在 Stackoverflow 中看到了许多链接,但找不到任何适用于 IE9 或更高版本的链接。就像@Terry Young 在 how-to-data-export-to-csv-using-jquery-or-javascript 中解释的那样

另外,试过——

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>';
        }

不知道如何修复它。我不想访问服务器并导出我的 CSV(要求是这样的)。

4

6 回答 6

18

使用 Javascript 后,它将解决您的问题。

将其用于 IE,

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

有关我编写的教程的更多信息,请参阅 -以 CSV 格式下载 JSON 数据 跨浏览器支持

希望这对您有所帮助。

于 2015-02-10T14:16:41.857 回答
7

对于 IE 10+,您可以执行以下操作:

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);

我不相信在早期版本的 IE 中这是可能的。不调用 activeX 对象,但如果可以接受,您可以使用:

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

这会将文件直接写入用户的文件系统。然而,这通常会提示用户询问他们是否要允许脚本运行。在 Intranet 环境中可以禁用该提示。

于 2014-06-25T20:09:39.090 回答
6

这也是我在 IE 10+ 版本中使用和工作得很好的答案之一:

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);
        }           
    }

希望这可以帮助。

于 2015-10-06T10:55:54.327 回答
4

我得到了支持 IE 8+ 的解决方案。我们需要指定分隔符,如下所示。

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();
  }  

您可以通过链接http://andrew-b.com/view/article/44

于 2014-11-12T12:39:51.390 回答
1

这适用于任何浏览器,无需 jQuery。

  1. 在页面的任意位置添加以下 iframe:

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

  2. 为要导出的页面中的表指定一个 id:

    <table id="dataTable">

  3. 自定义链接或按钮以调用 ExportToCsv 函数,将默认文件名和表 ID 作为参数传递。例如:

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

  4. 将此添加到您的 JavaScript 文件或部分:

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>andrew@me.com</td>
  </tr>
  <tr>
    <td>Bob</td>
    <td>32</td>
    <td>bob@me.com</td>
  </tr>
  <tr>
    <td>Sarah</td>
    <td>19</td>
    <td>sarah@me.com</td>
  </tr>
  <tr>
    <td>Anne</td>
    <td>25</td>
    <td>anne@me.com</td>
  </tr>
</table>

<a href="#" onclick="ExportToCsv('DefaultFileName', 'dataTable');return true;">Click this to download a .csv</a>

于 2015-04-17T11:31:26.650 回答
0

使用 Blob 对象创建一个 blob 对象并使用 msSaveBlob 或 msSaveOrOpenBlob 代码在 IE11 中工作(未针对其他浏览器测试)

    <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>
于 2016-09-03T14:59:45.393 回答