如何将JavaScript数组信息导出到csv(在客户端)? [英] How to export JavaScript array info to csv (on client side)?

查看:168
本文介绍了如何将JavaScript数组信息导出到csv(在客户端)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有很多这样的问题,但我需要使用JavaScript。我使用Dojo 1.8和所有的属性信息在数组,它看起来像这样:

  [[name1, city_name1,...] [name2,city_name2,...]] 

任何想法如何可以导出到客户端的csv?

解决方案

可以在本机JavaScript。您必须将数据解析为正确的CSV格式(假设您正在使用数组的数组数组,如您在问题中所述):

  var data = [[name1,city1,some other info],[name2,city2,more info]]; 
var csvContent =data:text / csv; charset = utf-8,;
data.forEach(function(infoArray,index){

dataString = infoArray.join(,);
csvContent + = index< data.length?dataString + \\\
:dataString;

});然后你可以使用JavaScript的 window.open
encodeURI
函数下载CSV文件,如下所示:

  var encodedUri = encodeURI(csvContent); 
window.open(encodedUri);

编辑:

如果您要为文件指定特定的名称必须做一些不同的事情,因为这不支持使用 window.open 方法访问数据URI。为了实现这一点,你可以创建一个隐藏的< a> DOM节点并设置它的下载

  var encodedUri = encodeURI(csvContent); 
var link = document.createElement(a);
link.setAttribute(href,encodedUri);
link.setAttribute(download,my_data.csv);
document.body.appendChild(link); //对于FF $ b必需

link.click(); //这将下载名为my_data.csv的数据文件。


I know there are lot of questions of this nature but I need to do this using JavaScript. I am using Dojo 1.8 and have all the attribute info in array, which looks like this:

[["name1", "city_name1", ...]["name2", "city_name2", ...]]

Any idea how I can export this to csv on the client side?

解决方案

You can do this in native JavaScript. You'll have to parse your data into correct CSV format as so (assuming you are using an array of arrays for your data as you have described in the question):

var data = [["name1", "city1", "some other info"], ["name2", "city2", "more info"]];
var csvContent = "data:text/csv;charset=utf-8,";
data.forEach(function(infoArray, index){

   dataString = infoArray.join(",");
   csvContent += index < data.length ? dataString+ "\n" : dataString;

}); 

Then you can use JavaScript's window.open and encodeURI functions to download the CSV file like so:

var encodedUri = encodeURI(csvContent);
window.open(encodedUri);

Edit:

If you want to give your file a specific name, you have to do things a little differently since this is not supported accessing a data URI using the window.open method. In order to achieve this, you can create a hidden <a> DOM node and set its download attribute as follows:

var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");
document.body.appendChild(link); // Required for FF

link.click(); // This will download the data file named "my_data.csv".

这篇关于如何将JavaScript数组信息导出到csv(在客户端)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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