当前位置: 首页 > news >正文

使用Handsontable实现动态表格和下载表格

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>

文章到此结束,希望对你有所帮助~

相关文章:

  • 基于MTF的1D-2D-CNN-LSTM-Attention时序图像多模态融合的故障识别,适合研究学习(Matlab完整源码和数据),附模型研究报告
  • DIY钢铁侠方舟反应堆第二期—第一代电路板展示
  • 【Hive入门】Hive基础操作与SQL语法:DDL操作全面指南
  • chrony服务器
  • 路由交换实验-手动聚合与LACP
  • Python爬虫学习:高校数据爬取与可视化
  • AIGC的商业化路径:哪些公司正在领跑赛道?
  • 页面滚动锚点也滚动-封装了一个ts方法(定位锚点跟随页面滚动下滑)
  • 前端渲染pdf文件解决方案-pdf.js
  • 工具指南:免费将 PDF 转换为 Word 的 10 个工具
  • MIT IDSS深度解析:跨学科融合与系统科学实践
  • 【白雪讲堂】GEO优化第7篇 -构建《推荐类》内容的结构化模板
  • 代码随想录训练营第39天 || 198. 打家劫舍 213. 打家劫舍 II 337. 打家劫舍 III
  • YOLO学习笔记 | 从YOLOv5到YOLOv11:技术演进与核心改进
  • 搭建 Stable Diffusion 图像生成系统并通过 Ngrok 暴露到公网(实现本地系统网络访问)——项目记录
  • 基于esp32-s3,写一个实现json键值对数据创建和读写解析c例程
  • HCIA-Access V2.5_18_网络管理基础_1_网络管理系统架构
  • 【AI】Trae的MCP配置及使用测试
  • 什么是 GLTF/GLB? 3D 内容创建的基本数据格式说明,怎么下载GLB/GLTF格式模型
  • 实现支付宝沙箱环境搭建
  • 航空货运三巨头去年净利合计超88亿元,密切关注关税政策变化和市场反应
  • 海南:谈话提醒9名缺点明显或有苗头性、倾向性问题的省管干部
  • 灰鹦鹉爆粗口三年未改?云南野生动物园:在持续引导
  • 网上销售假冒片仔癀和安宫牛黄丸,两人被判刑
  • 针对“二选一”,美团再次辟谣
  • 罗马教皇方济各去世,享年88岁