将 JavaScript 变量值转换为 csv 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17103398/
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
Convert JavaScript variable value to csv file
提问by RavatSinh Sisodiya
I have a comma separated variable in my .js file, for example:
我的 .js 文件中有一个逗号分隔的变量,例如:
var out='';
out+="1,val1,val2,val3,val4\n";
out+="2,val1,val2,val3,val4\n";
out+="3,val1,val2,val3,val4\n";
I am displaying this value in a browser using document.write(out);
.
I would like the out
variable to be downloadable as a .csv
file.
我在浏览器中使用document.write(out);
.
我希望该out
变量可以作为.csv
文件下载。
From data stored in a variable, is there any way to create a csv file and its associated download link in JavaScript?
从存储在变量中的数据,有没有办法在 JavaScript 中创建 csv 文件及其关联的下载链接?
jsFiddle
js小提琴
回答by Lee Kowalkowski
Depends on browser support, but that's getting pretty good with new browsers: http://jsfiddle.net/3fMeL/2/
取决于浏览器支持,但对于新浏览器来说这变得非常好:http: //jsfiddle.net/3fMeL/2/
var CSV = [
'"1","val1","val2","val3","val4"',
'"2","val1","val2","val3","val4"',
'"3","val1","val2","val3","val4"'
].join('\n');
window.URL = window.webkitURL || window.URL;
var contentType = 'text/csv';
var csvFile = new Blob([CSV], {type: contentType});
var a = document.createElement('a');
a.download = 'my.csv';
a.href = window.URL.createObjectURL(csvFile);
a.textContent = 'Download CSV';
a.dataset.downloadurl = [contentType, a.download, a.href].join(':');
document.body.appendChild(a);
So the first item is the Blob object, this creates the object that can be downloaded. https://developer.mozilla.org/en-US/docs/Web/API/Blob(http://caniuse.com/#search=blob)
所以第一项是 Blob 对象,这将创建可以下载的对象。https://developer.mozilla.org/en-US/docs/Web/API/Blob( http://caniuse.com/#search=blob)
The next part is the download attribute of the link, which informs the browser to download the CSV file rather than opening it in the browser window. (http://caniuse.com/#feat=download)
下一部分是链接的下载属性,它通知浏览器下载 CSV 文件而不是在浏览器窗口中打开它。( http://caniuse.com/#feat=download)
回答by Bhavesh Gangani
there is jquery plugin for output file at the client side without server side interaction,
客户端有输出文件的jquery插件,无需服务器端交互,