javascript - 无法将表导出为 csv

标签 javascript html csv

我想填充一个表格并将其导出为 csv。以下是我的代码

<html>
<head>
    <title></title>
</head>
<body>


<div class="container">
    <h1>Build Table</h1>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

    <div>
        <table id="blacklistgrid">
            <tr id="Row1">
                <td>Week Number</td>
                <td>Oranges Sold</td>
                <td>Apples Sold</td>
            </tr>
            <tr class="Row2">
                <td>
                    <input type="text"/>
                </td>
                <td>
                    <input type="text"/>
                </td>
                <td>
                    <input type="text"/>
                </td>
            </tr>
        </table>
        <button type="button" id="btnAdd">Add Row!</button>
        <button><a href="#" class="export">Export Table data into Excel</a></button>
    </div>

    <script>
     jQuery(document).ready(function () {
     jQuery('#btnAdd').click(function () {
          jQuery( ".Row2" ).clone().appendTo( "#blacklistgrid" );

        });
     });


$(document).ready(function() {

  function exportTableToCSV($table, filename) {

    var $rows = $table.find('tr:has(td)'),

      // Temporary delimiter characters unlikely to be typed by keyboard
      // This is to avoid accidentally splitting the actual contents
      tmpColDelim = String.fromCharCode(11), // vertical tab character
      tmpRowDelim = String.fromCharCode(0), // null character

      // actual delimiter characters for CSV format
      colDelim = '","',
      rowDelim = '"\r\n"',

      // Grab text from table into CSV formatted string
      csv = '"' + $rows.map(function(i, row) {
        var $row = $(row),
          $cols = $row.find('td');

        return $cols.map(function(j, col) {
          var $col = $(col),
            text = $col.text();

          return text.replace(/"/g, '""'); // escape double quotes

        }).get().join(tmpColDelim);

      }).get().join(tmpRowDelim)
      .split(tmpRowDelim).join(rowDelim)
      .split(tmpColDelim).join(colDelim) + '"';

    // Deliberate 'false', see comment below
    if (false && window.navigator.msSaveBlob) {

      var blob = new Blob([decodeURIComponent(csv)], {
        type: 'text/csv;charset=utf8'
      });

      // Crashes in IE 10, IE 11 and Microsoft Edge
      // See MS Edge Issue #10396033
      // Hence, the deliberate 'false'
      // This is here just for completeness
      // Remove the 'false' at your own risk
      window.navigator.msSaveBlob(blob, filename);

    } else if (window.Blob && window.URL) {
      // HTML5 Blob
      var blob = new Blob([csv], {
        type: 'text/csv;charset=utf-8'
      });
      var csvUrl = URL.createObjectURL(blob);

      $(this)
        .attr({
          'download': filename,
          'href': csvUrl
        });
    } else {
      // Data URI
      var csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);

      $(this)
        .attr({
          'download': filename,
          'href': csvData,
          'target': '_blank'
        });
    }
  }

  // This must be a hyperlink
  $(".export").on('click', function(event) {
    // CSV
    var args = [$('#blacklistgrid'), 'export.csv'];

    exportTableToCSV.apply(this, args);

    // If CSV, don't do event.preventDefault() or return false
    // We actually need this to be a typical hyperlink
  });
});


    </script>

</body>
</html>

我可以动态填充表格并添加行。但是,我似乎无法将填充的数据导出到 csv 文件。我做错了什么?

最佳答案

由于您使用的是输入元素,text()方法不起作用 - 本质上你的 <td> 之间没有任何东西元素。相反,您想使用 val()从所述输入元素获取文本的方法。这是一个简单的示例:https://jsfiddle.net/dzy5ktv6/

请注意,我将选择器更改为选择 input元素而不是 td .

关于javascript - 无法将表导出为 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42584150/

相关文章:

javascript - 数组中的对象包含特定值

javascript - 将 JavaScript 函数重写为类方法? ( typescript 可能)

javascript - PHP "strtotime(' -11 个月的 JS 等价物')"

php - 如何向 html 表格的列添加搜索和过滤器?

javascript - 如何使用 css 和 javascript 创建一个由弧段组成的圆?

javascript - JQuery TableSorter 重新加载和排序

parsing - 解析制表符分隔的字符串

javascript - 如何在 ReactJS 中将 button[type=submit] 添加到 React-ladda 按钮组件?

api - 所有货币的雅虎金融 API 列表

Java 流将 excel CSV 收集到基于列的总和过滤的列表中