1.效果
2.實現代碼
首先要加載Handsontable,在示例中我是cdn的方式引入的,vue的話需要下載插件
let hot = null;var exportPlugin = null;function showHandsontable(param) {const container = document.getElementById("hot-container");// 如果已有實例,先銷毀if (hot) {hot.destroy();}hot = new Handsontable(container, {data: [], // 初始為空colHeaders: true, // 動態列頭rowHeaders: true, // 動態行頭width: "100%",height: 800,licenseKey: "non-commercial-and-evaluation", // 免費版許可證contextMenu: true, // 啟用右鍵菜單manualColumnResize: true, // 允許調整列寬manualRowResize: true, // 允許調整行高filters: true, // 啟用篩選dropdownMenu: true, // 啟用下拉菜單columnSorting: true, // 啟用列排序stretchH: "all", // 列寬自適應afterChange: function (changes, source) {if (source === "edit") {console.log("數據已修改:", changes);}},});}showHandsontable();
點擊后開始加載數據,注意colHeaders,rowHeaders,是行和列的名稱,是數組格式
updateSettings:更新表格數據和表頭
loadData:重新加載數據
document.getElementById("load-data").addEventListener("click", async function () {try {const response = await mockApiCall();console.log(response, "這時候弄-");// 更新表格數據和表頭hot.updateSettings({colHeaders: response.headers.columns,rowHeaders: response.headers.rows,});hot.loadData(response.data);exportPlugin = hot.getPlugin("exportFile");console.log("數據加載成功");} catch (error) {console.error("加載數據失敗:", error);}
3.下載表格
主要用到downloadFile和hot.getPlugin("exportFile")下載格式為csv,目前在Handsontable官網沒有看到可以下載xlsx格式的,可能需要xlsx插件
button.addEventListener("click", () => {//下載表格的數據exportPlugin.downloadFile("csv", {bom: false,columnDelimiter: ",",columnHeaders: true,//顯示表頭exportHiddenColumns: true,exportHiddenRows: true,fileExtension: "csv",filename: "Handsontable-CSV-file_[YYYY]-[MM]-[DD]",mimeType: "text/csv",rowDelimiter: "\r\n",rowHeaders: true,});//改為下載報表接口數據});
4.完整代碼
<!DOCTYPE html>
<html lang="zh-CN"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>動態表格示例 - Handsontable</title><!-- <script src="./handsontable.full.min.js"></script><link rel="stylesheet" href="./handsontable.full.min.css" /> --><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/handsontable/15.0.0/handsontable.full.min.js"integrity="sha512-3Os2SFklHFmIWzqQsBOmpA9fYBiar8ASBI4hqgeUKttdJ6lDWli7W+JmXyN8exab8NOpiYT441s6hfqX6Tx+WA=="crossorigin="anonymous"referrerpolicy="no-referrer"></script><linkrel="stylesheet"href="https://cdnjs.cloudflare.com/ajax/libs/handsontable/15.0.0/handsontable.full.min.css"integrity="sha512-reELraG6l/OUbRy0EnDh2RxkanfohOkWJX7afyUG1aGHv49SA9uqrAcJOMhyCNW6kcwbnhePc6JKcdUsQxmjvw=="crossorigin="anonymous"referrerpolicy="no-referrer"/><style>body {font-family: Arial, sans-serif;margin: 20px;}#hot-container {margin-top: 20px;}.controls {margin-bottom: 10px;}button {padding: 8px 12px;margin-right: 10px;cursor: pointer;}</style></head><body><h1>動態表格示例</h1><div class="controls"><button id="load-data">加載數據</button><button id="export-file">下載表格</button></div><div id="hot-container"></div><!-- <script src="app.js"></script> --><script type="text/javascript">let hot = null;var exportPlugin = null;function showHandsontable(param) {const container = document.getElementById("hot-container");// 如果已有實例,先銷毀if (hot) {hot.destroy();}hot = new Handsontable(container, {data: [], // 初始為空colHeaders: true, // 動態列頭rowHeaders: true, // 動態行頭width: "100%",height: 800,licenseKey: "non-commercial-and-evaluation", // 免費版許可證contextMenu: true, // 啟用右鍵菜單manualColumnResize: true, // 允許調整列寬manualRowResize: true, // 允許調整行高filters: true, // 啟用篩選dropdownMenu: true, // 啟用下拉菜單columnSorting: true, // 啟用列排序stretchH: "all", // 列寬自適應afterChange: function (changes, source) {if (source === "edit") {console.log("數據已修改:", changes);}},});}showHandsontable();// 加載數據按鈕事件document.getElementById("load-data").addEventListener("click", async function () {try {const response = await mockApiCall();console.log(response, "這時候弄-");// 更新表格數據和表頭hot.updateSettings({colHeaders: response.headers.columns,rowHeaders: response.headers.rows,});hot.loadData(response.data);exportPlugin = hot.getPlugin("exportFile");console.log("數據加載成功");} catch (error) {console.error("加載數據失敗:", error);}});function mockApiCall() {return new Promise((resolve) => {// 模擬網絡延遲setTimeout(() => {const mockData = {headers: {columns: ["ID", "姓名", "年齡", "部門", "薪資"],rows: Array.from({ length: 15 }, (_, i) => `員工${i + 1}`),},data: Array.from({ length: 15 }, (_, i) => [i + 1000,`員工${i + 1}`,Math.floor(Math.random() * 20) + 20,["研發部", "市場部", "人事部", "財務部"][Math.floor(Math.random() * 4)],(Math.random() * 10000 + 5000).toFixed(2),]),};resolve(mockData);}, 500);});}const button = document.querySelector("#export-file");button.addEventListener("click", () => {//下載表格的數據exportPlugin.downloadFile("csv", {bom: false,columnDelimiter: ",",columnHeaders: false,exportHiddenColumns: true,exportHiddenRows: true,fileExtension: "csv",filename: "Handsontable-CSV-file_[YYYY]-[MM]-[DD]",mimeType: "text/csv",rowDelimiter: "\r\n",rowHeaders: true,});//改為下載報表接口數據});</script></body>
</html>
文章到此結束,希望對你有所幫助~