且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-05-01 22:15:20

您可以在原生 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访问数据 URI代码>方法.为了实现这一点,您可以创建一个隐藏的 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".