สำหรับการเพิ่มฟีเจอร์ Export to Excel เข้าไปใน TabulatorPlus นั้น คุณจำเป็นต้องใช้ Library ภายนอกที่ชื่อว่า xlsx ร่วมด้วย เพราะ Tabulator ใช้ตัวนี้เป็น Engine หลักในการสร้างไฟล์ครับ
🛠 การปรับปรุง TabulatorPlus.js
import { TabulatorFull as Tabulator } from 'tabulator-tables';
// Note: ในโปรเจกต์ของคุณต้องติดตั้ง npm install xlsx ด้วยครับ // ... (isObject และ deepMerge functions เหมือนเดิม) ... export default class TabulatorPlus extends Tabulator { constructor (el, userConfig = {}, storageKey = null) { const defaultConfig = { layout: "fitColumns", // ... (config อื่น ๆ เหมือนเดิม) ... // เพิ่มการตั้งค่าดาวน์โหลดเบื้องต้น downloadConfig: { columnGroups: false, // รวมกลุ่มคอลัมน์ไหม rowGroups: false, // รวมกลุ่มแถวไหม columnCalcs: true, // รวมผลรวมท้ายคอลัมน์ไหม }, }; const finalConfig = deepMerge (defaultConfig, userConfig) ; super (el, finalConfig) ; } /** * 5. Export to Excel Method * Downloads the current table data as an Excel file (.xlsx) * @param {string} fileName - The name of the file to be saved (default: "table-data") */ exportToExcel (fileName = "table-data") { // ตรวจสอบว่ามี Library xlsx ติดตั้งอยู่หรือไม่ (ป้องกัน Error) if (typeof window.XLSX === "undefined" && !require?.resolve ('xlsx')) { console.warn ("Tabulator requires the 'xlsx' library to export Excel files.") ; } // สั่ง Download โดยระบุประเภทเป็น "xlsx" this.download ("xlsx", `${fileName}.xlsx`, { sheetName: "MyData" }) ; } // ... (Method อื่น ๆ : globalSearch, refreshData, forceRedraw, resetFilters) ...
}
💡 วิธีใช้งานใน Framework ต่าง ๆ
เมื่อคุณมี Method นี้แล้ว คุณสามารถสร้างปุ่มใน UI แล้วสั่งงานได้ง่าย ๆ ครับ
ตัวอย่าง
// สมมติว่ามีปุ่ม Export ในหน้าจอ
const handleExport = () => { myTable.exportToExcel ("User_Report_2026") ;
};
✨ ทำไมฟีเจอร์นี้ถึงมีประโยชน์ ?
- WYSIWYG : Tabulator จะ Export ข้อมูลตามที่คุณเห็นในตาราง
- Customization: คุณสามารถระบุชื่อไฟล์ หรือแม้แต่ชื่อ Sheet ภายในไฟล์ Excel ได้
- No Extra Logic: คุณไม่ต้องเขียน Logic การสร้างตาราง Excel เองเลย แค่เรียก Method เดียว Library จะจัดการแปลง JSON เป็น Spreadsheet ให้ทันที
⚠️ ข้อควรระวัง
เพื่อให้ฟีเจอร์นี้ทำงานได้ คุณต้องมั่นใจว่าโปรเจกต์ของคุณมี Library xlsx อยู่ในระบบ
- แบบ NPM
npm install xlsx - แบบ CDN
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
อ่านเพิ่มเติม