// ==UserScript== // @name 网页表格导出工具 // @namespace http://tampermonkey.net/ // @version 0.2 // @description 为网页表格添加Excel导出功能,适合于下载任意网站或者像DeepSeek ChatGPT等生成的表格,导出按钮显示在表格右上角 // @author HiKey // @match *://*/* // @require https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js // @require https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js // @grant GM_addStyle // ==/UserScript== (function() { 'use strict'; // 添加简约按钮样式 GM_addStyle(` .export-btn-group { position: absolute; top: 2px; right: 2px; z-index: 1000; opacity: 0.8; transition: opacity 0.3s; } .export-btn-group:hover { opacity: 1; } .export-btn { padding: 3px 8px; background: rgba(76, 175, 80, 0.7); color: white; border: none; border-radius: 2px; cursor: pointer; font-size: 11px; font-family: Arial; box-shadow: 0 1px 3px rgba(0,0,0,0.1); transition: background 0.2s; } .export-btn:hover { background: rgba(68, 157, 68, 0.9); } `); // 处理表格 function processTables() { document.querySelectorAll('table').forEach(table => { if (table.dataset.processed) return; // 创建按钮容器 const btnGroup = document.createElement('div'); btnGroup.className = 'export-btn-group'; // 创建单个导出按钮 const btnXLSX = createButton('导出Excel', () => exportTable(table, 'xlsx')); btnGroup.append(btnXLSX); // 添加轻量级包装 const wrapper = document.createElement('div'); wrapper.style.position = 'relative'; wrapper.style.display = 'inline-block'; table.parentNode.insertBefore(wrapper, table); wrapper.appendChild(table); wrapper.appendChild(btnGroup); table.dataset.processed = true; }); } // 创建简洁按钮 function createButton(text, onClick) { const btn = document.createElement('button'); btn.className = 'export-btn'; btn.textContent = text; btn.title = '点击导出为Excel文件'; btn.addEventListener('click', onClick); return btn; } // 导出功能 function exportTable(table, type) { const title = document.title.replace(/[^a-zA-Z0-9]/g, '_').substring(0, 30); const timestamp = new Date().toISOString().slice(0, 10); const wb = XLSX.utils.book_new(); const ws = XLSX.utils.table_to_sheet(table); XLSX.utils.book_append_sheet(wb, ws, '数据'); XLSX.writeFile(wb, `${title}_${timestamp}.xlsx`); } // 优化初始化逻辑 const init = () => { processTables(); new MutationObserver(mutations => { mutations.forEach(mutation => { if (mutation.addedNodes.length) processTables(); }); }).observe(document.body, { childList: true, subtree: true }); }; if (document.readyState === 'complete') init(); else window.addEventListener('load', init); })();