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

标签 javascript jquery csv

我正在尝试将数组转换为可以粘贴到 Excel CSV 文件中的行。在下面的代码中,我能够按照我想要的方式格式化数组内容(在//return csvFile; 行)。就在那之后,我试图创建一个隐藏的输入,将 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 < 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;
    var $temp = $("<input>");
    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 = $("<textarea id='temp'>").text(csvFile);
  $("body").append($temp)
  $("#temp").select();
  var result = document.execCommand("copy");
  $("#temp").remove();
  return result?"Copied to clipboard":"Clipboard failed...";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="copy">Copy</button>

这不是:

console.clear();
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 < 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 = $("<textarea id='temp'>").text(csvFile);
  $("body").append($temp)
  $("#temp").select();
  var result = document.execCommand("copy");
  $("#temp").remove();
  return result?"Copied to clipboard":"Clipboard failed...";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于Javascript:将数组转换为 CSV 格式并复制到剪贴板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51471433/

相关文章:

javascript - 有没有办法在将 .ejs 文件渲染到 .html 文件的同时运行函数?

javascript - WebKit 高度差异

javascript - 单击背景时淡出 JavaScript "modal window"?

php - CSV 到 Mysql 插入日期时间

javascript - 基于 id/class 的选择器与基于表单的选择器

javascript - 如何比较过滤器的两个对象数组

javascript - 从事件页面更改选项卡的 DOM

javascript - 在表单下使用 .html() 动态插入隐藏文本字段未通过

java - 使用类路径在 java 中加载 CSV

python - 如何使用 csv.DictReader 在 django 中上传和读取 csv 文件?