如何将JavaScript数组信息导出到csv(在客户端)?

本文翻译自:How to export JavaScript array info to csv (on client side)?

I know there are lot of questions of this nature but I need to do this using JavaScript. 我知道有很多这种性质的问题,但是我需要使用JavaScript来完成。 I am using Dojo 1.8 and have all the attribute info in array, which looks like this: 我正在使用Dojo 1.8并在数组中具有所有属性信息,如下所示:

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

Any idea how I can export this to CSV on the client side? 知道如何将其导出到客户端的CSV吗?


#1楼

参考:https://stackoom.com/question/10mpP/如何将JavaScript数组信息导出到csv-在客户端


#2楼

You can do this in native JavaScript. 您可以在本机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): 您必须这样将数据解析为正确的CSV格式(假设您正在使用问题中所描述的数组数组):

const rows = [
    ["name1", "city1", "some other info"],
    ["name2", "city2", "more info"]
];

let csvContent = "data:text/csv;charset=utf-8,";

rows.forEach(function(rowArray) {
    let row = rowArray.join(",");
    csvContent += row + "\r\n";
});

or the shorter way (using arrow functions ): 或更短的方法(使用箭头功能 ):

const rows = [
    ["name1", "city1", "some other info"],
    ["name2", "city2", "more info"]
];

let csvContent = "data:text/csv;charset=utf-8," 
    + rows.map(e => e.join(",")).join("\n");

Then you can use JavaScript's window.open and encodeURI functions to download the CSV file like so: 然后,您可以使用JavaScript的window.openencodeURI函数来下载CSV文件,如下所示:

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. 如果要为文件指定一个特定的名称,则必须做一些不同的事情,因为不支持使用window.open方法访问数据URI。 In order to achieve this, you can create a hidden <a> DOM node and set its download attribute as follows: 为了实现这一点,您可以创建一个隐藏的<a> DOM节点并按如下所示设置其download属性:

 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". 

#3楼

The solution from @Default works perfect on Chrome (thanks a lot for that!) but I had a problem with IE. @Default的解决方案在Chrome上运行完美(非常感谢!),但是IE出现问题。

Here's a solution (works on IE10): 这是一个解决方案(适用于IE10):

var csvContent=data; //here we load our csv data 
var blob = new Blob([csvContent],{
    type: "text/csv;charset=utf-8;"
});

navigator.msSaveBlob(blob, "filename.csv")

#4楼

I came here looking for a bit more RFC 4180 compliance and I failed to find an implementation, so I made a (possibly inefficient) one for my own needs. 我是来这里寻求RFC 4180的更多合规性的,但是我找不到实现方法,因此我根据自己的需要制作了一个(可能效率不高)的方法。 I thought I would share it with everyone. 我以为我会和大家分享。

var content = [['1st title', '2nd title', '3rd title', 'another title'], ['a a a', 'bb\nb', 'cc,c', 'dd"d'], ['www', 'xxx', 'yyy', 'zzz']];

var finalVal = '';

for (var i = 0; i < content.length; i++) {
    var value = content[i];

    for (var j = 0; j < value.length; j++) {
        var innerValue =  value[j]===null?'':value[j].toString();
        var result = innerValue.replace(/"/g, '""');
        if (result.search(/("|,|\n)/g) >= 0)
            result = '"' + result + '"';
        if (j > 0)
            finalVal += ',';
        finalVal += result;
    }

    finalVal += '\n';
}

console.log(finalVal);

var download = document.getElementById('download');
download.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(finalVal));
download.setAttribute('download', 'test.csv');

Hopefully this will help someone out in the future. 希望这会在将来对某人有所帮助。 This combines both the encoding of the CSV along with the ability to download the file. 这结合了CSV的编码和下载文件的功能。 In my example on jsfiddle . 在我的jsfiddle例子中。 You can download the file (assuming HTML 5 browser) or view the output in the console. 您可以下载文件(假设使用HTML 5浏览器)或在控制台中查看输出。

UPDATE: 更新:

Chrome now appears to have lost the ability to name the file. Chrome现在似乎失去了命名文件的功能。 I'm not sure what's happened or how to fix it, but whenever I use this code (including the jsfiddle), the downloaded file is now named download.csv . 我不确定发生了什么或如何解决它,但是每当我使用此代码(包括jsfiddle)时,下载的文件现在都名为download.csv


#5楼

In Chrome 35 update, download attribute behavior was changed. 在Chrome 35更新中,下载属性行为已更改。

https://code.google.com/p/chromium/issues/detail?id=373182 https://code.google.com/p/chromium/issues/detail?id=373182

to work this in chrome, use this 要在chrome中使用,请使用

var pom = document.createElement('a');
var csvContent=csv; //here we load our csv data 
var blob = new Blob([csvContent],{type: 'text/csv;charset=utf-8;'});
var url = URL.createObjectURL(blob);
pom.href = url;
pom.setAttribute('download', 'foo.csv');
pom.click();

#6楼

//It work in Chrome and IE ... I reviewed and readed a lot of answer. then i used it and tested in both ... 

var link = document.createElement("a");

if (link.download !== undefined) { // feature detection
    // Browsers that support HTML5 download attribute
    var blob = new Blob([CSV], { type: 'text/csv;charset=utf-8;' });
    var url = URL.createObjectURL(blob);            
    link.setAttribute("href", url);
    link.setAttribute("download", fileName);
    link.style = "visibility:hidden";
}

if (navigator.msSaveBlob) { // IE 10+
   link.addEventListener("click", function (event) {
     var blob = new Blob([CSV], {
       "type": "text/csv;charset=utf-8;"
     });
   navigator.msSaveBlob(blob, fileName);
  }, false);
}

document.body.appendChild(link);
link.click();
document.body.removeChild(link);

//Regards
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值