Javascript:将数组转换为CSV格式并复制到剪贴板

我正在尝试将数组转换为可以粘贴到Excel文件中的行。 在下面的代码中,我能够按照我想要的格式化数组内容(在//返回csvFile; line)。 就在那之后,我正在尝试创建一个隐藏的输入,将csvFile的内容添加到它,选择元素中的文本并复制,但它不起作用。 这是我的代码:

var array = [ [0,1,1,0], [1,0,0,1], [1,0,0,1], [0,1,1,0] ]; var string = copyCsv(array); console.log(string); function copyCsv(rows) { var processRow = function (row) { var finalVal = ''; for (var j = 0; j = 0) result = '"' + result + '"'; if (j > 0) finalVal += ','; finalVal += result; } return finalVal + '\n'; }; var csvFile = "\ufeff"+''; for (var i = 0; i < rows.length; i++) { csvFile += processRow(rows[i]); } //return csvFile; var $temp = $(""); csvFile.append($temp); $temp.val($(element).text()).select(); document.execCommand("copy"); $temp.remove(); } 

你可以在这里找到我的JsFiddle: https ://jsfiddle.net/xpvt214o/464368/

谢谢,

.select()需要在DOM附加的元素上完成,以便execCommand()复制它。

另外,现代浏览器不允许复制到剪贴板而无需用户单击来触发它。

我使用了textarea元素,因为有多行….

这有效:

 console.clear(); var array = [ [0,1,1,0], [1,0,0,1], [1,0,0,1], [0,1,1,0] ]; // A button to trigger the copy action. $("#copy").on("click",function(){ var string = copyCsv(array); console.log(string); }); function copyCsv(rows) { var processRow = function (row) { var finalVal = ''; for (var j = 0; j < row.length; j++) { var innerValue = row[j] === null ? '' : row[j].toString(); if (row[j] instanceof Date) { innerValue = row[j].toLocaleString(); }; var result = innerValue.replace(/"/g, '""'); if (result.search(/("|,|\n)/g) >= 0) result = '"' + result + '"'; if (j > 0) finalVal += ','; finalVal += result; } return finalVal + '\n'; }; var csvFile = "\ufeff"+''; for (var i = 0; i < rows.length; i++) { csvFile += processRow(rows[i]); } console.log(csvFile); //return csvFile; var $temp = $(" 
   

如果我理解你的问题。 您想将CSV格式添加到输入隐藏字段中。

我稍微修改了你的代码

 function copyCsv(rows) { var processRow = function (row) { var finalVal = ''; for (var j = 0; j < row.length; j++) { var innerValue = row[j] === null ? '' : row[j].toString(); if (row[j] instanceof Date) { innerValue = row[j].toLocaleString(); }; var result = innerValue.replace(/"/g, '""'); if (result.search(/("|,|\n)/g) >= 0) result = '"' + result + '"'; if (j > 0) finalVal += ','; finalVal += result; } return finalVal + '\n'; }; var csvFile = "\ufeff"+''; for (var i = 0; i < rows.length; i++) { csvFile += processRow(rows[i]); } //return csvFile; console.log(csvFile); var x = document.createElement("INPUT"); x.setAttribute("type", "hidden"); x.setAttribute("id", "myHiddenData"); document.body.appendChild(x); document.getElementById("myHiddenData").value = csvFile; document.execCommand("copy"); var copyText = document.getElementById("myHiddenData"); document.execCommand("copy"); copyText.select(); /* Copy the text inside the text field */ document.execCommand("copy"); alert("Copied the text: " + copyText.value); } 

工作小提琴