



function exporttableToCSV(tableId, filename) { const table = document.getElementById(tableId); if (!table) { console.error("Table not found!"); return; } let csv = []; const rows = table.querySelectorAll('tr'); rows.forEach(row => { let rowData = []; const cols = row.querySelectorAll('td, th'); // 兼容th和td cols.forEach(col => { let text = col.innerText.replace(/"/g, '""'); // 處理雙引號 if (text.includes(',') || text.includes('n')) { // 處理逗號和換行符 text = `"${text}"`; } rowData.push(text); }); csv.push(rowData.join(',')); }); const csvString = csv.join('n'); const blob = new Blob([csvString], { type: 'text/csv;charset=utf-8;' }); const link = document.createElement('a'); if (link.download !== undefined) { // feature detection for download attribute const url = URL.createObjectURL(blob); link.setAttribute('href', url); link.setAttribute('download', filename || 'table_data.csv'); link.style.visibility = 'hidden'; document.body.appendChild(link); link.click(); document.body.removeChild(link); } } // 調用示例:exportTableToCSV('myTable', 'my_report.csv');
// 假設你已經引入了html2canvas庫 function shareTableAsImage(tableId) { const table = document.getElementById(tableId); if (!table) { console.error("Table not found!"); return; } html2canvas(table, { scale: window.devicePixelRatio, // 提高清晰度 logging: false, // 關閉日志 useCORS: true // 如果表格內有跨域圖片,需要這個 }).then(canvas => { // canvas.toDataURL() 可以得到圖片的Base64編碼 // 接下來你可以將這個Base64編碼的圖片上傳到服務器,獲取URL后進行分享 // 或者直接嘗試使用Web Share API分享Data URL (不推薦,因為太長且兼容性差) // 更實際的做法是,生成圖片后,提供下載或上傳到圖床再分享 const imgUrl = canvas.toDataURL('image/png'); // 比如,提供一個下載鏈接 const link = document.createElement('a'); link.href = imgUrl; link.download = 'table_snapshot.png'; document.body.appendChild(link); link.click(); document.body.removeChild(link); // 也可以嘗試直接分享,但通常需要用戶點擊觸發 // if (navigator.share) { // canvas.toBlob(blob => { // const file = new File([blob], 'table.png', { type: 'image/png' }); // navigator.share({ // files: [file], // title: '我的表格數據', // text: '這是一份從網頁導出的表格數據截圖。' // }).catch(error => console.log('分享失敗', error)); // }, 'image/png'); // } }).catch(err => { console.error("Error generating image:", err); }); }
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END