问题描述
我知道有很多这样的问题,但我需要使用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
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 thewindow.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(在客户端)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!