将javascript数据导出到CSV文件,无需服务器交互 [英] Export javascript data to CSV file without server interaction

查看:235
本文介绍了将javascript数据导出到CSV文件,无需服务器交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们在nodeJS服务器上,我们可以编写一个标头,设置一个mime类型,并发送它:

If we were on a nodeJS server, we could write a header, set a mime type, and send it:

res.header("Content-Disposition", "attachment;filename="+name+".csv"); 
res.type("text/csv");
res.send(200, csvString);

由于标题,浏览器将为命名的csv文件创建下载。

and because of the headers, the browser will create a download for the named csv file.

当在浏览器中生成有用数据时,将其置于CSV文件中的一种解决方案是使用ajax,将其上传到服务器,(可选择将其保存在那里)并获取服务器使用这些标头将其发回以在浏览器中成为csv下载。

When useful data is generated in a browser, one solution to getting it in a CSV file is to use ajax, upload it to the server, (perhaps optionally save it there) and get the server to send it back with these headers to become a csv download back at the browser.

但是,我想要一个不涉及ping的100%浏览器解决方案 - pong with the server。

However, I would like a 100% browser solution that does not involve ping-pong with the server.

因此我发现可以打开一个新窗口并尝试使用等效的META标记设置标题。

So it occurred to me that one could open a new window and try to set the header with a META tag equivalent.

但在最近的Chrome中,这对我不起作用。

But this doesn't work for me in recent Chrome.

我有一个新窗口,它包含csvString,但不作为下载。

I do get a new window, and it contains the csvString, but does not act as a download.

我想我希望在底部标签中下载或在底部标签中下载一个空白的新窗口。

I guess I expected to get either a download in a bottom tab or a blank new window with a download in a bottom tab.

我想知道元标记是否正确或是否还需要其他标记。

I'm wondering if the meta tags are correct or if other tags are also needed.

是否存在一种方法可以使这项工作没有将它发送到服务器?

Is there a way to make this work without punting it to the server?

JsFiddle在浏览器中创建CSV(不工作 - 输出窗口但没有下载)

var A = [['n','sqrt(n)']];  // initialize array of rows with header row as 1st item
for(var j=1;j<10;++j){ A.push([j, Math.sqrt(j)]) }
var csvRows = [];
for(var i=0,l=A.length; i<l; ++i){
    csvRows.push(A[i].join(','));   // unquoted CSV row
}
var csvString = csvRows.join("\n");
console.log(csvString);
var csvWin = window.open("","","");
csvWin.document.write('<meta name="content-type" content="text/csv">');
csvWin.document.write('<meta name="content-disposition" content="attachment;  filename=data.csv">  ');
csvWin.document.write(csvString);


推荐答案

总有HTML5 download attribute:

There's always the HTML5 download attribute :


此属性(如果存在)表示作者打算将
超链接用于下载资源,以便当用户
点击链接时,系统会提示他们将其保存为本地文件。

This attribute, if present, indicates that the author intends the hyperlink to be used for downloading a resource so that when the user clicks on the link they will be prompted to save it as a local file.

如果属性有值,则使用该值作为用户单击
链接时打开的保存提示中的预填充
文件名。

If the attribute has a value, the value will be used as the pre-filled file name in the Save prompt that opens when the user clicks on the link.



var A = [['n','sqrt(n)']];

for(var j=1; j<10; ++j){ 
    A.push([j, Math.sqrt(j)]);
}

var csvRows = [];

for(var i=0, l=A.length; i<l; ++i){
    csvRows.push(A[i].join(','));
}

var csvString = csvRows.join("%0A");
var a         = document.createElement('a');
a.href        = 'data:attachment/csv,' +  encodeURIComponent(csvString);
a.target      = '_blank';
a.download    = 'myFile.csv';

document.body.appendChild(a);
a.click();

FIDDLE

在Chrome和Firefox中测试,在最新版本中运行良好(截至2013年7月) )

也适用于Opera,但不设置文件名(截至2013年7月)

似乎没有在IE9中工作(大惊喜)(截至2013年7月)

Tested in Chrome and Firefox, works fine in the newest versions (as of July 2013).
Works in Opera as well, but does not set the filename (as of July 2013).
Does not seem to work in IE9 (big suprise) (as of July 2013).

可以找到有关哪些浏览器支持下载属性的概述 这里

对于不支持的浏览器,必须设置合适的浏览器服务器端的标题。

An overview over what browsers support the download attribute can be found Here
For non-supporting browsers, one has to set the appropriate headers on the serverside.

显然有 IE10和IE11的黑客入侵,它不支持下载属性(但是)

Apparently there is a hack for IE10 and IE11, which doesn't support the download attribute (Edge does however).

var A = [['n','sqrt(n)']];

for(var j=1; j<10; ++j){ 
    A.push([j, Math.sqrt(j)]);
}

var csvRows = [];

for(var i=0, l=A.length; i<l; ++i){
    csvRows.push(A[i].join(','));
}

var csvString = csvRows.join("%0A");

if (window.navigator.msSaveOrOpenBlob) {
    var blob = new Blob([csvString]);
    window.navigator.msSaveOrOpenBlob(blob, 'myFile.csv');
} else {
    var a         = document.createElement('a');
    a.href        = 'data:attachment/csv,' +  encodeURIComponent(csvString);
    a.target      = '_blank';
    a.download    = 'myFile.csv';
    document.body.appendChild(a);
    a.click();
}

这篇关于将javascript数据导出到CSV文件,无需服务器交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆