Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

javascript - 如何将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吗?)   ask by Sam007 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...