HTML table export to CSV

常常遇到上司想在網頁上方便觀看一些搜集而來的數據,之後又說想要把網頁上的表格匯出成 csv 檔案,方便他們用 excel 計算一些東西。這時候該怎麼辦才好?



以下為使用 jQuery 的解決方案

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();

          if(/^(0)([0-9]){9}/.test(text)){
            return '=""'+text.replace(/"/g, '""')+'""';  // 如果是0開頭純數字的10碼手機號碼, =""+phone+"" 可以強制string顯示
          }else{
            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("\ufeff"+csv)], {
        type: 'text/csv;charset=utf-8'
      });

      // 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(["\ufeff"+csv], {
        type: 'text/csv;charset=utf-8'
      });
      var csvUrl = URL.createObjectURL(blob);

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

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

  // This must be a html <a> tag
  $(".export").on('click', function(event) {
    // CSV
    var args = [$('#dvData>table'), '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
  });

來源: Export to CSV using jQuery and html



與來源不一樣的地方在於,我自己有再加上 \ufeff 避免輸出是亂碼,還有 =""+phone+"" 簡易的0開頭手機號碼 string 顯示。希望能解決各位的問題。


留言

這個網誌中的熱門文章

用CSS的 min() max() 與vw,設計有極限值的RWD響應式文字

10 steps to Create「Lil Yachty meme」AI generated Video (Viggle AI)

運用資料層 dataLayer.push 建立 GTM 自訂事件