Handsontable 表格组件的使用

发布于:2025-04-20 ⋅ 阅读:(18) ⋅ 点赞:(0)

Handsontable 是一个强大的 JavaScript 表格组件,类似于 Excel,支持 数据绑定、单元格编辑、排序、筛选、验证、合并单元格等功能,适用于 Web 端的数据表格管理。

https://handsontable.com/

1. 安装 Handsontable

  • 方式 1:使用 npm 安装
npm install handsontable
  • 方式 2:通过 CDN 引入
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/handsontable/dist/handsontable.full.min.css">
<script src="https://cdn.jsdelivr.net/npm/handsontable/dist/handsontable.full.min.js"></script>

2. 创建一个基本表格

<div id="example"></div>

<script>
  // 获取 HTML 元素
  var container = document.getElementById('example');

  // 初始化 Handsontable
  var hot = new Handsontable(container, {
    data: [
      ["张三", 25, "男"],
      ["李四", 30, "女"],
      ["王五", 28, "男"]
    ],
    colHeaders: ["姓名", "年龄", "性别"],  // 列标题
    rowHeaders: true,  // 显示行号
    width: "100%",
    height: 300,
    licenseKey: "non-commercial-and-evaluation" // 许可证(免费版)
  });
</script>

这是个基本的表格,可直接编辑单元格。

3. 主要配置

3.1、 data 数据

支持 数组 或 对象数组:

data: [
  { name: "张三", age: 25, gender: "男" },
  { name: "李四", age: 30, gender: "女" }
]

3.2、 columns 指定列配置

columns: [
  { data: "name", type: "text" },
  { data: "age", type: "numeric" },
  { data: "gender", type: "dropdown", source: ["男", "女"] }
]

✅ 作用:指定列类型,支持 文本、数字、下拉框、日期、复选框等。

4. Handsontable 高级功能

4.1、 添加排序

columnSorting: true  // 允许点击表头排序

4.2、 过滤数据

dropdownMenu: true,   // 启用下拉菜单
filters: true         // 启用过滤

4.3、 选中行高亮

selectionMode: 'multiple'  // 允许多选

4.4、 只读单元格

cells: function (row, col) {
  if (col === 1) { // 让第2列只读
    return { readOnly: true };
  }
}

4.5、 校验数据

columns: [
  {
    data: "age",
    type: "numeric",
    validator: function (value, callback) {
      callback(value > 0 && value < 100); // 限制年龄在 1-99 之间
    }
  }
]

5. Handsontable 与 Vue结合

Vue 使用 Handsontable
安装 Vue 版本:

npm install @handsontable/vue

使用:

<template>
  <HotTable :data="tableData" :colHeaders="['姓名', '年龄', '性别']" :columns="columns" />
</template>

<script>
import { HotTable } from "@handsontable/vue";
import "handsontable/dist/handsontable.full.css";

export default {
  components: { HotTable },
  data() {
    return {
      tableData: [
        { name: "张三", age: 25, gender: "男" },
        { name: "李四", age: 30, gender: "女" }
      ],
      columns: [
        { data: "name", type: "text" },
        { data: "age", type: "numeric" },
        { data: "gender", type: "dropdown", source: ["男", "女"] }
      ]
    };
  }
};
</script>

6. 总结

功能 配置项
基本表格 data
列标题 colHeaders
行号 rowHeaders
排序 columnSorting: true
筛选 filters: true
只读 cells: { readOnly: true }
数据校验 validator
Vue/React @handsontable/vue、@handsontable/react

🚀 Handsontable 适用于各种数据表格管理场景,提供 Excel 级别的编辑体验!

在这里插入图片描述


不管活成什么样子,都不要把责任推给别人。一切的苦乐都是自己造成的,任何一次选择,都有他对应的筹码,愿赌服输也是一个成年人该有的品质。。



网站公告

今日签到

点亮在社区的每一天
去签到