Javascript/ jQuery:以 CSV 格式导出数据在 IE 中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18185660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript/ jQuery : Exporting data in CSV not working in IE
提问by Shubh
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.
我需要将表中显示的数据导出为 CSV 格式。我已经尝试了很多东西,但无法让它在 IE 9 及更高版本上工作。
I have created a dummy fiddlewith 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
我在 Stackoverflow 中看到了许多链接,但找不到任何适用于 IE9 或更高版本的链接。就像@ Terry Young 在 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).
不知道如何修复它。我不想访问服务器并导出我的 CSV(要求是这样说的)。
采纳答案by inaam husain
After using Javascript it will solve your problem.
使用 Javascript 后,它将解决您的问题。
Use this for IE,
将此用于 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
有关我编写的教程的更多信息,请参阅 -下载 CSV 格式的 JSON 数据跨浏览器支持
Hope this will be helpful for you.
希望这对你有帮助。
回答by Adam Matthews
For IE 10+ you can do:
对于 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);
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:
我不相信它在早期版本的 IE 中是可能的。不调用 activeX 对象,但如果可以接受,您可以使用:
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.
这会将文件直接写入用户的文件系统。然而,这通常会提示用户询问他们是否允许脚本运行。可以在 Intranet 环境中禁用提示。
回答by arunsingh
This is also one of the answers which I used and working great for IE 10+ versions :
这也是我使用过的并且对 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);
}
}
Hope this helps.
希望这可以帮助。
回答by user3679149
I got the solution for it which is supporting IE 8+ for me. We need to specify the separator as shown below.
我得到了支持 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();
}
You can go through the link http://andrew-b.com/view/article/44
回答by Marco Lackovic
This will work on any browser, without the need of jQuery.
这将适用于任何浏览器,无需 jQuery。
Add the following iframe anywhere in your page:
<iframe id="CsvExpFrame" style="display: none"></iframe>
Give an id to the table in the page you want to export:
<table id="dataTable">
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')"/>
Add this to your JavaScript file or section:
在页面的任意位置添加以下 iframe:
<iframe id="CsvExpFrame" style="display: none"></iframe>
为要导出的页面中的表指定一个 id:
<table id="dataTable">
自定义您的链接或按钮以调用 ExportToCsv 函数,将默认文件名和表的 id 作为参数传递。例如:
<input type="button" onclick="ExportToCsv('DefaultFileName','dataTable')"/>
将此添加到您的 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>[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>
回答by Nikita
use Blob object Create a blob object and use msSaveBlob or msSaveOrOpenBlob The code is working in IE11 (not tested for other browsers)
使用 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>