Greasy Fork 支持简体中文。

Download Table as CSV

Add a download button at the top of every html table to download / export it as a CSV (comma seperated values) file

  1. // ==UserScript==
  2. // @name Download Table as CSV
  3. // @namespace Violentmonkey Scripts
  4. // @match *://*/*
  5. // @grant none
  6. // @version 1.9
  7. // @author igorlogius
  8. // @description Add a download button at the top of every html table to download / export it as a CSV (comma seperated values) file
  9. // ==/UserScript==
  10.  
  11. (function(){
  12.  
  13. // simulate click event
  14. function simulateClick(elem) {
  15. var evt = new MouseEvent('click', {
  16. bubbles: true,
  17. cancelable: true,
  18. view: window
  19. });
  20. var canceled = !elem.dispatchEvent(evt);
  21. }
  22.  
  23. // get closest table parent
  24. function getTableParent(node){
  25. while ( node = node.parentNode,
  26. node !== null && node.tagName !== 'TABLE' );
  27. return node;
  28. }
  29.  
  30. // assemble csv data
  31. function getTblData(tbl){
  32. // csv store
  33. var csv = [];
  34. // get all rows inside the table
  35. tbl.querySelectorAll('tr').forEach(function(trRow) {
  36. // Only process direct tr children
  37. if( ! tbl.isEqualNode(getTableParent(trRow))){
  38. return;
  39. }
  40. // assemble row content
  41. var row = [];
  42. trRow.querySelectorAll('td, th').forEach(function(col) {
  43. // remove multiple spaces and linebreaks (breaks csv)
  44. var data = col.innerText.replace(/(\r\n|\n|\r)/gm, '').replace(/(\s\s)/gm, ' ')
  45. // escape double-quote with double-double-quote
  46. data = data.replace(/"/g, '""');
  47. row.push('"' + data + '"');
  48. });
  49. csv.push(row.join(','));
  50. });
  51. return csv.join('\n');
  52. }
  53.  
  54. // add button + click action
  55. function add_btn(tbl){
  56. var btn = document.createElement('button');
  57. btn.innerHTML = 'Download Table as CSV';
  58. btn.setAttribute('type', 'button');
  59. // Process Table on Click
  60. btn.onclick = function() {
  61. var csv_string = getTblData(tbl);
  62. csvlink.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv_string));
  63. simulateClick(csvlink);
  64. };
  65. // Insert before Table
  66. tbl.parentNode.insertBefore(btn,tbl);
  67. }
  68.  
  69. /* *
  70. * M A I N
  71. * */
  72.  
  73. // add link
  74. var csvlink = document.createElement('a');
  75. csvlink.style.display = 'none';
  76. csvlink.setAttribute('target', '_blank');
  77. csvlink.setAttribute('download', 'data.csv');
  78. document.body.append(csvlink);
  79.  
  80. // add buttons
  81. document.querySelectorAll('table').forEach(function(tbl){add_btn(tbl)});
  82. }());