我需要知道很多关于JavaScript的问题.我使用Dojo 1.8,数组中有所有属性信息,如下所示:

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

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

推荐答案

您可以在本机JavaScript中实现这一点.您必须将数据解析为正确的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";
});

或者用更短的方法(使用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");

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

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

编辑:

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相关问答推荐

Angular 拦截器错误处理删除方法问题

Angular:ng-contract未显示

为什么在集内和集外会产生不同的promise 状态(使用Promise.race)?

如何将拖放功能添加到我已自定义为图像的文件输入HTML标签中?

vanillajs-datepicker未设置输入值,日期单击时未触发更改事件

vscode扩展-webView Panel按钮不起任何作用

如何将连续的十六进制字符串拆分为以空间分隔的十六进制块,每个十六进制块包含32个二元组?

从mat—country—select获取整个Country数组

如何解决CORS政策的问题

将2D数组转换为图形

将自定义排序应用于角形数字数组

当作为表达式调用时,如何解析方法decorator 的签名?

在拖放时阻止文件打开

Websocket错误—有一个或多个保留位开启:reserved1 = 1,reserved2 = 0,reserved3 = 0

第三方包不需要NODE_MODULES文件夹就可以工作吗?

Use Location位置成员在HashRouter内为空

JS Animate()方法未按预期工作

无法设置RazorPay订阅API项目价格

我怎样才能得到一个数组的名字在另一个数组?

Plotly.js栏为x轴栏添加辅助文本