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

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

问题描述

我知道有很多这种性质的问题,但我需要使用 JavaScript 来解决这个问题.我正在使用 Dojo 1.8 并将所有属性信息放在数组中,如下所示:

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

知道如何在客户端将其导出到 CSV 吗?

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

推荐答案

您可以在原生 JavaScript 中执行此操作.您必须将您的数据解析为正确的 CSV 格式(假设您使用的是问题中描述的数组数组):

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):

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 + "
";
});

或更短的方法(使用 箭头函数):

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("
");

然后您可以使用 JavaScript 的 window.openencodeURI 函数来下载 CSV 文件,如下所示:

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);

如果你想给你的文件一个特定的名字,你必须做一些不同的事情,因为这不支持使用 window.open方法.为了实现这一点,您可以创建一个隐藏的 DOM 节点并设置其 download 属性如下:

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天全站免登陆