首页 > 其他分享 >好用的js表格组件tabulator使用

好用的js表格组件tabulator使用

时间:2024-09-24 09:34:55浏览次数:10  
标签:false name title js field table tabulator true 好用

偶然中看到了这个功能强大的表格组件,不仅支持分页、过滤、排序、树形表格等常见的功能,且支持分组显示、表格内编辑、统计计算、读本地文件、拖拽表格改变行列顺序、下载、像在excel文件中操作一样的编辑等多种功能。

常用配置项及表格实例化

查看代码
<link href="../plugins/tabulator/css/tabulator.min.css" rel="stylesheet" />
<div id="table"></div>
<script type="text/javascript" language="javascript" src="../plugins/tabulator/js/tabulator.min.js"></script>
<script type="text/javascript" language="javascript" src="../plugins/luxon.min.js"></script>
<script type="text/javascript" language="javascript" src="data.js"></script>
<script>
  const cus_formatter = {
    nameFormatter: function (cell, formatterParams) {
      const value = cell.getValue();
      if (value.indexOf("o") > 0) {
        return "<span style='color:#3FB449; font-weight:bold;'>" + value + "</span>";
      } else {
        return value;
      }
    },
  };

  const table = new Tabulator("#table", {
    //通用表格配置
    // height: "311px",
    minHeight: 300,
    maxHeight: 500,
    // renderVdertical: "virtual",
    // renderHorizontal: "basic",
    placeholder: "No Data Set", //无数据时显示的内容
    history: false, //禁用用户交互历史功能
    locale: "zh_CN", //本地化配置
    // downloadConfig: {}, //指定下载文件中包含的列内容
    downloadRowRange: "active", //指定下载文件中包含的行
    validationMode: "blocking", //指定表格验证模式
    textDirection: "auto", //指定表格的文本方向

    //列属性
    //通用:title field visible
    //布局:hozAlign vertAlign headerHozAlign width minWidth maxWidth widthGrow widthShrink frozen responsive tooltip cssClass print clipboard
    //数据操作:sorter sorterParams formatter formatterParams editable editor editorParams editorEmptyValue editorEmptyValueFunc validator download titleDownload topCalc bottomCalc
    //列头:headerSort headerTooltip headerVertical headerWordWrap headerFilter
    //内置的formatter:plaintext textarea html money image link datetime(依赖于luxon.js库) tickCross color star traffic progress lookup toggle buttonTick buttonCross rownum rowSelection
    //内置的editor:input textarea number range tickCross star progress date(依赖于luxon.js库) time datetime list
    //内置的验证器:required unique integer float numeric string alphanumeric min:5 max:5 minLength:5 maxLength:5 in:red|green|blue starts:bob ends:green regex:\\.com$
    //内置的sorter:string number alphanum exists date(依赖于luxon.js库) time datetime array
    columns: [
      { title: "Name", field: "name", width: 200, headerSort: false, formatter: cus_formatter.nameFormatter, editor: "input", validator: ["required"] },
      { title: "Progress", field: "progress", sorter: "number", sorter: "number", editor: true, validator: ["min:0", "max:100", "numeric"] },
      { title: "Location", field: "location", headerSort: false, editable: true, editor: "list", editorParams: { autocomplete: "true", allowEmpty: true, listOnEmpty: true, valuesLookup: true } },
      { title: "Gender", field: "gender", editor: "list", editorParams: { values: { male: "Male", female: "Female", unknown: "Unknown" } }, validator: ["required", "in:male|female"] },
      { title: "Rating", field: "rating", sorter: "number", formatter: "star", formatterParams: { stars: 6 }, editor: true, validator: ["min:0", "max:5", "integer"] },
      { title: "Driver", field: "car", hozAlign: "center", formatter: "tickCross", editor: true },
      { title: "Favourite Color", field: "col", formatter: "color", editor: true, validator: ["minLength:3", "maxLength:10", "string"] },
      {
        title: "Date Of Birth",
        field: "dob",
        hozAlign: "center",
        widthGrow: 1.2,
        editor: "date",
        sorter: "date",
      },
      { formatter: "buttonCross", hozAlign: "center", headerSort: false },
    ],
    //默认的列属性配置
    columnDefaults: {
      hozAlign: "left",
      vertAlign: "middle",
      headerHozAlign: "center",
      resizable: true,
    },
    //打开自动列、配置自动列的显示
    // autoColumns: true,
    // autoColumnsDefinitions: function (definitions) {
    //   definitions.forEach((column) => {
    //     column.headerFilter = true; // add header filter to every column
    //   });

    //   return definitions;
    // },
    layout: "fitColumns", //表格列布局模式
    layoutColumnsOnNewData: true, //数据载入时改变表格的宽度以适应数据
    responsiveLayout: false, //自动隐藏/显示列以适应表格元素的宽度
    // responsiveLayoutCollapseStartOpen: [], //responsiveLayout开启时显示为折叠列列表
    movableColumns: false, //允许用户移动和重新排序的列的列表
    columnHeaderVertAlign: "middle", //头内容垂直对齐
    columnCalcs: true, //表中列计算器的显示位置
    headerVisible: true, //表头显示
    resizableColumnFit: true, //调整列大小时保持总列宽
    // rowHeight: 20, //定义行高
    autoResize: false, //禁用自动调整表格大小
    resizableRows: false, //不允许用户手动调整行高
    resizableRowGuide: true,
    resizableColumnGuide: true,

    //行标题的列定义
    rowHeader: {
      headerSort: false,
      frozen: true,
      headerHozAlign: "center",
      hozAlign: "center",
      formatter: "rownum",
    },
    addRowPos: "bottom", //新增行放置的位置

    movableRows: false, //不允许用户移动和重新排序行
    movableColumns: false, //不允许用户移动和重新排序列

    //数据
    index: "id", //用作每行唯一索引的字段
    data: tabledata, //数据
    ajaxURL: false,
    filterMode: "local", //数据过滤模式
    sortMode: "local", //排序模式
    dataLoader: true, //加载数据时显示加载器,也可以接受必须返回布尔值的函数
    // dataLoaderLoading: "loading...", //加载器元素的html
    // dataLoaderError: "error", //发生错误时加载器元素的html
    // dataLoaderErrorTimeout: 3000, //发生错误时显示加载器错误消息的毫秒数

    //排序
    initialSort: [{ column: "id", dir: "asc" }],
    sortOrderReverse: false,

    //过滤
    initialFilter: [{ field: "id", type: ">=", value: 2 }],

    //行分组
    groupBy: false,
    groupValues: [],

    //分页
    pagination: true,
    paginationMode: "local",
    paginationSize: 6,
    paginationSizeSelector: [3, 6, 8, 10],
    paginationButtonCount: 5,
    paginationInitialPage: 1,
    paginationAddRow: "table",
    paginationCounter: "rows",

    langs: {
      zh_CN: {
        columns: {
          name: "名字",
          location: "位置",
          progress: "进度",
          gender: "性别",
          rating: "比率",
          col: "最喜欢的颜色",
          dob: "出生日期",
          car: "是否有车",
        },
        data: {
          loading: "加载中",
          error: "出现了错误",
        },
        pagination: {
          page_size: "页码",
          page_title: "显示页",
          first: "第一页",
          first_title: "第一页",
          last: "最后一页",
          last_title: "最后一页",
          prev: "前一页",
          prev_title: "前一页",
          next: "前一页",
          next_title: "前一页",
          all: "全部",
          counter: {
            showing: "显示",
            of: "共",
            rows: "条",
            pages: "pages",
          },
        },
      },
    },

    //Spreadsheet
    spreadsheet: false,

    reactiveData: true, //代开此项配置后,对数据的改变将自动作用于表格中

    // frozenRows: 2, //冻结表格前2行

    selectableRows: true, //启用行选择

    //启用剪切板
    clipboard: true,
    clipboardCopyStyled: false,
    clipboardCopyRowRange: "selected",
    clipboardCopyConfig: {
      columnHeaders: false,
      columnGroups: false,
      rowHeaders: false,
      rowGroups: false,
      columnCalcs: false,
      dataTree: false,
      formatCells: false,
    },
    clipboardPasteAction: "replace",
    clipboardPasteParser: "range", //use the range parser

    //打印
    printAsHtml: true,
    printStyled: true,
    printRowRange: "selected",
    printHeader: "<h1>Example Table Header<h1>",
    printFooter: "<h2>Example Table Footer<h2>",
    printConfig: {
      columnHeaders: false,
      columnGroups: false,
      rowHeaders: false,
      rowGroups: false,
      columnCalcs: false,
      dataTree: false,
      formatCells: false,
    },
  });
</script>

常用api

查看代码
 table.setData(tableData); //从数组中加载数据
table.replaceData(tabledata); //静默替代表中所有数据
table.updateData(data); //更新数据
table.addData(data); //新增数据
table.updateOrAddData(data); //存在则更新数据,否则将新增数据
table.clearData(); //清除数据
table.addRow({ name: "Billy Bob" }, true); //新增一行数据
table.updateRow(1, { id: 1, name: "bob", gender: "male" }); //更新数据
table.updateOrAddRow(3, { id: 3, name: "steve", gender: "male" }); //存在则更新数据,否则将新增数据
table.deleteRow(15); //删除行数据
table.deleteRow([15, 7, 9]); //删除行数据

const data_all = table.getData(); //获取所有数据;
const data_active = table.getData("active"); //获取过滤后的数据;
const rowCount = table.getDataCount(); //获取数据行数;
const rowCount1 = table.getDataCount("active"); //获取过滤后的数据行数;
const row_idx = table.getRow(1); //获取指定行元素
const rowData = row.getData(); //获取行数据
const rows_all = table.getRows(); //获取所有行元素
const rows_active = table.getRows("active"); //获取过滤后的行元素
const rows_se = table.searchRows("age", ">", 12); //检索行元素
const data = table.searchData("age", ">", 12); //检索行数据
const position = table.getRowPosition(row); //依据行元素获取位置
const row = table.getRowFromPosition(5); //依据位置获取行元素
const htmlTable = table.getHtml(); //获取html table,可通过配置htmlOutputConfig配置
const htmlTable_filter = table.getHtml("visible", true, { columnGroups: false });

//sorter
table.setSort("age", "asc");
table.setSort([
    { column: "age", dir: "asc" },
    { column: "height", dir: "desc" },
]);
table.getSorters();
table.clearSort();

//内置的filter
table.setFilter("name", "=", "Steve");
table.setFilter("name", "!=", "Steve");
table.setFilter("name", "like", "Steve");
table.setFilter("colors", "keywords", "red green blue");
table.setFilter("tags", "keywords", "red green blue", { matchAll: true });
table.setFilter("name", "starts", "ste");
table.setFilter("name", "ends", "son");
table.setFilter("age", "<", 10);
table.setFilter("age", "<=", 10);
table.setFilter("age", ">=", 10);
table.setFilter("age", "in", ["steve", "bob", "jim"]);
table.setFilter("age", "regex", /[a-z]/);
table.setFilter([
    { field: "age", type: ">", value: 52 },
    { field: "name", type: "in", value: ["steve", "bob", "jim"] },
]);
table.setFilter([
    { field: "age", type: ">", value: 52 },
    [
        { field: "height", type: "<", value: 142 },
        { field: "name", type: "=", value: "steve" },
    ],
]);
table.addFilter("age", ">", 22);
table.refreshFilter();
table.removeFilter("age", ">", 22);
var filters = table.getFilters();
table.clearFilter();
table.clearHeaderFilter();

//列计算
table.recalc(); //重新计算
var results = table.getCalcResults();

//行选择
table.selectRow(1);
table.deselectRow(1);
table.selectRow();
table.deselectRow();

//历史操作
table.undo(); //撤销操作,需要配置项中history开启
table.redo();
table.clearHistory();

//打印
table.print(false, true);

常用event事件

查看代码
 table.on("dataLoading", function (data) {
    //data - the data loading into the table
});

table.on("dataLoaded", function (data) {
    console.log("data has been loaded");
});

table.on("dataLoadError", function (error) {
    console.log(error);
});

table.on("dataChanged", function (data) {
    //data - the updated table data
});

// table.on("dataProcessed", dataProcessedEvent);
// table.off("dataProcessed", dataProcessedEvent);

table.on("tableBuilding", function () {});

table.on("tableBuilt", () => {
    table.setPage(1);

    // table.setColumns(newColumns) //覆盖原来的列配置
    // table.updateColumnDefinition("name", {title:"Updated Title"})  //修改列配置
    // table.addColumn({ title: "Age", field: "age" }, true, "name");  //增加列配置
    // table.deleteColumn("name"); //删除列配置
    // const colDefs = table.getColumnDefinitions(); //获取列定义

    // table.showColumn("name");
    // table.hideColumn("name");
    // table.getColumn("name").hide();
    // table.toggleColumn("name");
});

table.on("tableDestroyed", function () {});

table.on("validationFailed", function (cell, value, validators) {
    console.log(cell, value, validators);
});

table.on("rowClick", function (e, row) {
    console.log("Row " + row.getData().id + " Clicked!!!!");
});

table.on("rowAdded", function (row) {
    //row - row component
});

table.on("rowUpdated", function (row) {
    //row - row component
});

table.on("rowDeleted", function (row) {
    //row - row component
});

table.on("rowSelected", function (row) {
    //row - row component for the selected row
});

table.on("rowDeselected", function (row) {
    //row - row component for the deselected row
});

table.on("rowSelectionChanged", function (data, rows, selected, deselected) {
    //rows - array of row components for the currently selected rows in order of selection
    //data - array of data objects for the currently selected rows in order of selection
    //selected - array of row components that were selected in the last action
    //deselected - array of row components that were deselected in the last action
});

table.on("cellEditing", function (cell) {
    //cell - cell component
});

table.on("cellEditCancelled", function (cell) {
    //cell - cell component
});

table.on("cellEdited", function (cell) {
    //cell - cell component
});

window.addEventListener("resize", function () {
    table.redraw();
});

基本表格

查看代码
 <link href="../plugins/tabulator/css/tabulator.min.css" rel="stylesheet" />
<style>
  div[id^="table"] {
    margin-bottom: 2rem;
  }
</style>
<div>
  <button id="reactivity-add">Add New Row</button>
  <button id="reactivity-delete">Remove Row</button>
  <button id="reactivity-update">Update First Row Name</button>
  <button id="get-data">get data</button>
</div>
<div id="table"></div>
<div id="table-checked"></div>
<script type="text/javascript" language="javascript" src="../plugins/tabulator/js/tabulator.min.js"></script>
<script type="text/javascript" language="javascript" src="../plugins/luxon.min.js"></script>
<script type="text/javascript" language="javascript" src="data.js"></script>

<script>
  const cus_formatter = {
    nameFormatter: function (cell, formatterParams) {
      const value = cell.getValue();
      if (value.indexOf("o") > 0) {
        return "<span style='color:#3FB449; font-weight:bold;'>" + value + "</span>";
      } else {
        return value;
      }
    },
  };

  const table = new Tabulator("#table", {
    // height: "355px",
    placeholder: "No Data Set", //无数据时显示的内容
    locale: "zh_CN", //本地化配置
    downloadRowRange: "active", //指定下载文件中包含的行
    validationMode: "blocking", //指定表格验证模式

    editTriggerEvent: "dblclick",

    columns: [
      { title: "Name", field: "name", width: 200, headerSort: false, formatter: cus_formatter.nameFormatter, editor: "input", validator: ["required"] },
      { title: "Progress", field: "progress", sorter: "number", sorter: "number", editor: true, validator: ["min:0", "max:100", "numeric"] },
      { title: "Location", field: "location", headerSort: false, editable: true, editor: "list", editorParams: { autocomplete: "true", allowEmpty: true, listOnEmpty: true, valuesLookup: true } },
      { title: "Gender", field: "gender", editor: "list", editorParams: { values: { male: "Male", female: "Female", unknown: "Unknown" } }, validator: ["required", "in:male|female"] },
      { title: "Rating", field: "rating", sorter: "number", formatter: "star", formatterParams: { stars: 6 }, editor: true, validator: ["min:0", "max:5", "integer"] },
      { title: "Driver", field: "car", hozAlign: "center", formatter: "tickCross", editor: true },
      { title: "Favourite Color", field: "col", headerSort: false, formatter: "color", editor: true, validator: ["minLength:3", "maxLength:10", "string"] },
      {
        title: "Date Of Birth",
        field: "dob",
        hozAlign: "center",
        widthGrow: 1.2,
        editor: "date",
        sorter: "date",
        sorterParams: {
          format: "yyyy-MM-dd",
          alignEmptyValues: "top",
        },
      },
      { formatter: "buttonCross", hozAlign: "center", headerSort: false },
    ],
    //默认的列属性配置
    columnDefaults: {
      hozAlign: "left",
      vertAlign: "middle",
      headerHozAlign: "center",
      resizable: true,
    },
    layout: "fitColumns", //表格列布局模式
    layoutColumnsOnNewData: true, //数据载入时改变表格的宽度以适应数据
    columnHeaderVertAlign: "middle", //头内容垂直对齐
    resizableRows: false, //此项配置打开和editor一起使用时容易造成行高样式混乱

    //行标题的列定义
    rowHeader: {
      headerSort: false,
      frozen: true,
      headerHozAlign: "center",
      hozAlign: "center",
      formatter: "rownum",
    },
    addRowPos: "bottom", //新增行放置的位置

    //数据
    index: "id", //用作每行唯一索引的字段
    data: tabledata, //数据
    ajaxURL: false,
    filterMode: "local", //数据过滤模式
    sortMode: "local", //排序模式
    dataLoader: true, //加载数据时显示加载器,也可以接受必须返回布尔值的函数

    //排序
    initialSort: [{ column: "id", dir: "asc" }],
    sortOrderReverse: false,

    //过滤
    initialFilter: [{ field: "id", type: ">=", value: 0 }],

    //分页
    pagination: true,
    paginationMode: "local",
    paginationSize: 10,
    paginationSizeSelector: [10, 25, 50, true],
    paginationButtonCount: 5,
    paginationInitialPage: 1,
    paginationAddRow: "table",
    paginationCounter: "rows",

    langs: {
      zh_CN: {
        columns: {
          name: "名字",
          location: "位置",
          progress: "进度",
          gender: "性别",
          rating: "比率",
          col: "最喜欢的颜色",
          dob: "出生日期",
          car: "是否有车",
        },
        data: {
          loading: "加载中",
          error: "出现了错误",
        },
        pagination: {
          page_size: "页码",
          page_title: "显示页",
          first: "第一页",
          first_title: "第一页",
          last: "最后一页",
          last_title: "最后一页",
          prev: "前一页",
          prev_title: "前一页",
          next: "前一页",
          next_title: "前一页",
          all: "全部",
          counter: {
            showing: "显示",
            of: "共",
            rows: "条",
            pages: "pages",
          },
        },
      },
    },

    reactiveData: true, //代开此项配置后,对数据的改变将自动作用于表格中
  });

  table.on("cellEdited", function (cell) {
    console.log(cell.getData());
  });

  document.getElementById("reactivity-add").addEventListener("click", function () {
    tabledata.push({ name: "IM A NEW ROW", progress: 100, gender: "male" });
  });
  document.getElementById("reactivity-delete").addEventListener("click", function () {
    tabledata.pop();
  });
  document.getElementById("reactivity-update").addEventListener("click", function () {
    tabledata[0].name = "IVE BEEN UPDATED";
  });

  document.getElementById("get-data").addEventListener("click", function () {
    const data = table.getData();
    console.log(data);
  });
</script>
<script>
  const data = [
    { id: 1, name: "Billy Bob", progress: "12", gender: "male", rating: 1, col: "red", dob: "", driver: 1 },
    { id: 2, name: "Mary May", progress: "1", gender: "female", rating: 2, col: "blue", dob: "14/05/1982", driver: true },
    { id: 3, name: "Christine Lobowski", progress: "42", rating: 0, col: "green", dob: "22/05/1982", driver: "true" },
    { id: 4, name: "Brendon Philips", progress: "125", gender: "male", rating: 1, col: "orange", dob: "01/08/1980" },
    { id: 5, name: "Margret'Marmajuke", progress: "16", gender: "female", rating: 5, col: "yellow", dob: "31/01/1999" },
  ];

  const table_checked = new Tabulator("#table-checked", {
    // height: "355px",

    columns: [
      { title: "Name", field: "name", width: 200, headerSort: false, formatter: cus_formatter.nameFormatter },
      { title: "Progress", field: "progress", sorter: "number", sorter: "number" },
      { title: "Location", field: "location", headerSort: false },
      { title: "Gender", field: "gender" },
      { title: "Rating", field: "rating", sorter: "number" },
      { title: "Driver", field: "car", hozAlign: "center", formatter: "tickCross" },
      { title: "Favourite Color", field: "col" },
      {
        title: "Date Of Birth",
        field: "dob",
        hozAlign: "center",
        widthGrow: 1.2,
        sorter: "date",
        formatter: "datetime",
        formatterParams: {
          inputFormat: "dd/MM/yyyy",
          outputFormat: "yyyy-MM-dd",
          invalidPlaceholder: "(invalid date)",
          timezone: "Asia/Shanghai",
        },
      },
      { formatter: "buttonCross", hozAlign: "center", headerSort: false },
    ],
    //默认的列属性配置
    columnDefaults: {
      hozAlign: "left",
      vertAlign: "middle",
      headerHozAlign: "center",
      resizable: true,
    },
    layout: "fitColumns", //表格列布局模式

    //行标题的列定义
    rowHeader: {
      headerSort: false,
      frozen: true,
      headerHozAlign: "center",
      hozAlign: "center",
      formatter: "rowSelection",
      titleFormatter: "rowSelection",
      cellClick: function (e, cell) {
        cell.getRow().toggleSelect();
      },
    },

    data: data, //数据
  });
</script>

data.js

查看代码
 const tabledata = [
  { id: 1, name: "Oli Bob", progress: 5, location: "United Kingdom", gender: "male", rating: 1, car: 1, col: "red", dob: "1984-04-14" },
  { id: 2, name: "Mary May", progress: 53, location: "Germany", gender: "female", rating: 2, car: 1, col: "blue", dob: "1982-05-14" },
  { id: 3, name: "Christine Lobowski", progress: 45, location: "France", gender: "female", rating: 0, car: 1, col: "green", dob: "1982-03-25" },
  { id: 4, name: "Brendon Philips", progress: 23, location: "USA", gender: "male", rating: 1, car: 0, col: "orange", dob: "1980-01-08" },
  { id: 5, name: "Margret Marmajuke", progress: 34, location: "Canada", gender: "female", rating: 5, car: 1, col: "yellow", dob: "1999-01-31" },
  { id: 6, name: "Frank Harbours", progress: 56, location: "Russia", gender: "male", rating: 4, car: 0, col: "red", dob: "1966-05-12" },
  { id: 7, name: "Jamie Newhart", progress: 65, location: "India", gender: "male", rating: 3, car: 1, col: "green", dob: "1985-05-14" },
  { id: 8, name: "张三", progress: 53, location: "China", gender: "female", rating: 0, car: 0, col: "red", dob: "1982-05-22" },
  { id: 9, name: "Emily Sykes", progress: 12, location: "South Korea", gender: "female", rating: 0, car: 1, col: "maroon", dob: "1970-11-11" },
  { id: 10, name: "James Newman", progress: 76, location: "Japan", gender: "male", rating: 5, car: 1, col: "red", dob: "1998-05-30" },
  { id: 11, name: "李四", progress: 76, location: "China", gender: "male", rating: 5, car: 1, col: "red", dob: "1998-04-30" },
];

ajax数据源

查看代码
 <link href="../plugins/tabulator/css/tabulator_semanticui.min.css" rel="stylesheet" />
<style>
  div[id^="table"] {
    margin-bottom: 2rem;
  }
</style>
<div id="table-ajax1"></div>
<div id="table-con">
  <table id="table-ajax2">
    <thead>
      <tr>
        <th>Name</th>
        <th>Progress</th>
        <th>Gender</th>
        <th>Rating</th>
        <th>Favourite Color</th>
        <th>Date Of Birth</th>
        <th>Driver</th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>
</div>
<script type="text/javascript" language="javascript" src="../plugins/tabulator/js/tabulator.min.js"></script>
<script>
  const columns_def = [
    { title: "Name", field: "name", sorter: "string", width: 200 },
    { title: "Progress", field: "progress", sorter: "number" },
    { title: "Gender", field: "gender", sorter: "string" },
    { title: "Rating", field: "rating", formatter: "star", hozAlign: "center", width: 100 },
    { title: "Favourite Color", field: "col", sorter: "string" },
    { title: "Date Of Birth", field: "dob", sorter: "date", hozAlign: "center" },
    { title: "Driver", field: "car", hozAlign: "center", formatter: "tickCross", sorter: "boolean" },
  ];
  //ajax加载数据
  const ajaxConfig = {
    method: "POST",
  };
  const table1 = new Tabulator("#table-ajax1", {
    minHeght: "350px",
    maxHeight: "450px",
    layout: "fitColumns",

    ajaxURL: "../../php-demos/request_json.php", //ajax URL
    ajaxParams: { key1: "value1", key2: "value2" }, //ajax 参数
    ajaxConfig: ajaxConfig,
    ajaxResponse: function (url, params, response) {
      return response;
    },
    progressiveLoad: "load", //load模式,数据量较大时使用,按顺序加载每页数据到表格中
    progressiveLoadDelay: 200, //每个请求间隔200ms
    // progressiveLoad: "scroll", //scroll模式,用户滚动时将数据加载到表中
    // progressiveLoadScrollMargin: 300, //当滚动条距离表格底部300px或更低时,触发下一次ajax加载。

    placeholder: "No Data Set",
    columns: columns_def,
  });

  const table2 = new Tabulator("#table-ajax2", {
    minHeght: "350px",
    maxHeight: "450px",
    layout: "fitColumns",

    placeholder: "No Data Set",
    columns: columns_def,
  });
  table2.on("tableBuilt", () => {
    table2.setData("../../php-demos/request_json.php", { mode: "data" }, ajaxConfig);
  });
</script>

 request_json.php

查看代码
 <?php

$data = [
    ['id' => 1, 'name' => "Billy Bob", 'progress' => "12", 'gender' => "male", 'rating' => 1, 'col' => "red", 'dob' => "", 'driver' => 1],
    ['id' => 2, 'name' => "Mary May", 'progress' => "1", 'gender' => "female", 'rating' => 2, 'col' => "blue", 'dob' => "14/05/1982", 'driver' => true],
    ['id' => 3, 'name' => "Christine Lobowski", 'progress' => "42", 'rating' => 0, 'col' => "green", 'dob' => "22/05/1982", 'driver' => "true"],
    ['id' => 4, 'name' => "Brendon Philips", 'progress' => "125", 'gender' => "male", 'rating' => 1, 'col' => "orange", 'dob' => "01/08/1980"],
    ['id' => 5, 'name' => "Margret'Marmajuke", 'progress' => "16", 'gender' => "female", 'rating' => 5, 'col' => "yellow", 'dob' => "31/01/1999"],
];

if (isset($_REQUEST['mode']) && $_REQUEST['mode'] == 'data') {
    echo json_encode($data);
} else {
    echo json_encode(["last_page" => 2, "data" => $data]);
}

 

html、本地文件数据源

查看代码
 <link href="../plugins/tabulator/css/tabulator_bulma.min.css" rel="stylesheet" />
<style>
  div[id^="table"] {
    margin-bottom: 2rem;
  }
</style>
<div id="table-con">
  <table id="table-html">
    <thead>
      <tr>
        <th width="200">Name</th>
        <th>Age</th>
        <th>Gender</th>
        <th>Height</th>
        <th>Favourite Color</th>
        <th>Date of Birth</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Billy Bob</td>
        <td>12</td>
        <td>male</td>
        <td>1</td>
        <td>red</td>
        <td></td>
      </tr>
      <tr>
        <td>Mary May</td>
        <td>1</td>
        <td>female</td>
        <td>2</td>
        <td>blue</td>
        <td>14/05/1982</td>
      </tr>
    </tbody>
  </table>
</div>
<div id="table-array"></div>
<button id="json-load-trigger">load form json</button>
<button id="csv-load-trigger">load form csv</button>
<button id="xlsx-load-trigger">load form xlsx</button>
<div id="table-file"></div>
<script type="text/javascript" language="javascript" src="../plugins/tabulator/js/tabulator.min.js"></script>
<script type="text/javascript" language="javascript" src="../plugins/xlsx.full.min.js"></script>
<script>
  //从html table加载数据
  const table_html = new Tabulator("#table-html", { layout: "fitColumns" });

  // 加载array数据
  const arrayData = [
    ["Name", "Age", "Likes Cheese"], //column header titles
    ["Bob", 23, true],
    ["Jim", 44, false],
  ];
  const table_array = new Tabulator("#table-array", {
    layout: "fitColumns",
    data: arrayData,
    importFormat: "array",
    autoTables: true,
    autoColumns: true,
  });

  const table_file = new Tabulator("#table-file", {
    height: "350px",
    layout: "fitColumns",
    autoColumns: true,
    placeholder: "等待数据,请上传文件",
  });

  // 加载json数据
  document.getElementById("json-load-trigger").addEventListener("click", function () {
    table_file.import("json", ".json");
  });

  // 加载csv数据
  document.getElementById("csv-load-trigger").addEventListener("click", function () {
    table_file.import("csv", ".csv");
  });

  // 加载XLSX数据 需引入 SheetJS Library 的xlsx.full.min.js文件
  document.getElementById("xlsx-load-trigger").addEventListener("click", function () {
    table_file.import("xlsx", [".xlsx", ".csv", ".ods"], "buffer");
  });
</script>

 

数据过滤

查看代码
 <link href="../plugins/tabulator/css/tabulator_materialize.min.css" rel="stylesheet" />
<div id="table-header-filter"></div>
<script type="text/javascript" language="javascript" src="../plugins/tabulator/js/tabulator.min.js"></script>
<script type="text/javascript" language="javascript" src="../plugins/luxon.min.js"></script>
<script type="text/javascript" language="javascript" src="data.js"></script>
<script>
  const minMaxFilterEditor = function (cell, onRendered, success, cancel, editorParams) {
    const container = document.createElement("span");

    const start = document.createElement("input");
    start.setAttribute("type", "number");
    start.setAttribute("placeholder", "Min");
    start.setAttribute("min", 0);
    start.setAttribute("max", 100);
    start.style.padding = "4px";
    start.style.width = "50%";
    start.style.boxSizing = "border-box";

    start.value = cell.getValue();

    function buildValues() {
      success({
        start: start.value,
        end: end.value,
      });
    }

    function keypress(e) {
      if (e.keyCode == 13) {
        buildValues();
      }

      if (e.keyCode == 27) {
        cancel();
      }
    }

    const end = start.cloneNode();
    end.setAttribute("placeholder", "Max");

    start.addEventListener("change", buildValues);
    start.addEventListener("blur", buildValues);
    start.addEventListener("keydown", keypress);

    end.addEventListener("change", buildValues);
    end.addEventListener("blur", buildValues);
    end.addEventListener("keydown", keypress);

    container.appendChild(start);
    container.appendChild(end);

    return container;
  };

  function minMaxFilterFunction(headerValue, rowValue, rowData, filterParams) {
    if (rowValue) {
      if (headerValue.start != "") {
        if (headerValue.end != "") {
          return rowValue >= headerValue.start && rowValue <= headerValue.end;
        } else {
          return rowValue >= headerValue.start;
        }
      } else {
        if (headerValue.end != "") {
          return rowValue <= headerValue.end;
        }
      }
    }

    return true;
  }

  const table = new Tabulator("#table-header-filter", {
    height: "500px",
    layout: "fitColumns",
    editTriggerEvent: "dblclick",
    columns: [
      { title: "Name", field: "name", headerFilter: "input" },
      {
        title: "Progress",
        field: "progress",
        headerFilter: minMaxFilterEditor,
        headerFilterFunc: minMaxFilterFunction,
        headerFilterLiveFilter: false,
      },
      {
        title: "Gender",
        field: "gender",
        editor: "list",
        editorParams: { values: { male: "Male", female: "Female" }, clearable: true },
        headerFilter: true,
        headerFilterParams: { values: { male: "Male", female: "Female" }, clearable: true },
      },
      { title: "Rating", field: "rating", editor: "star", hozAlign: "center", headerFilter: "number", headerFilterPlaceholder: "at least...", headerFilterFunc: ">=" },
      { title: "Favourite Color", field: "col", editor: "input", headerFilter: "list", headerFilterParams: { valuesLookup: true, clearable: true } },
      {
        title: "Date Of Birth",
        field: "dob",
        hozAlign: "center",
        headerFilter: "input",
      },
      {
        title: "Driver",
        field: "car",
        hozAlign: "center",
        formatter: "tickCross",
        headerFilter: "tickCross",
        headerFilterParams: { tristate: true },
        headerFilterEmptyCheck: function (value) {
          return value === null;
        },
      },
    ],
    data: tabledata,
  });
</script>

分组、树形表格

查看代码
 <link href="../plugins/tabulator/css/tabulator_bootstrap5.min.css" rel="stylesheet" />
<style>
  div[id^="table"] {
    margin-bottom: 2rem;
  }
</style>
<div id="table-sp-thead"></div>
<div id="table-group"></div>
<div id="table-group2"></div>
<div id="table-tree"></div>
<script type="text/javascript" language="javascript" src="../plugins/tabulator/js/tabulator.min.js"></script>
<script type="text/javascript" language="javascript" src="data.js"></script>
<script>
  const table_sp_thead = new Tabulator("#table-sp-thead", {
    layout: "fitColumns",
    columnHeaderVertAlign: "bottom",
    columns: [
      { title: "Name", field: "name" },
      {
        title: "Work Info",
        columns: [
          { title: "Progress", field: "progress", hozAlign: "right", sorter: "number" },
          { title: "Rating", field: "rating", hozAlign: "center" },
          { title: "Driver", field: "car", hozAlign: "center" },
        ],
      },
      {
        title: "Personal Info",
        columns: [
          { title: "Gender", field: "gender" },
          { title: "Favourite Color", field: "col" },
          { title: "Date Of Birth", field: "dob", hozAlign: "center", sorter: "date" },
        ],
      },
    ],
    data: tabledata,
  });
</script>
<script>
  const table_group = new Tabulator("#table-group", {
    layout: "fitColumns",
    groupBy: "gender",
    // groupBy: function (data) {
    //   return data.gender + " - " + data.age;
    // },
    groupStartOpen: true,
    groupToggleElement: "header",
    columns: [
      { title: "Name", field: "name", width: 200 },
      { title: "Progress", field: "progress", sorter: "number" },
      { title: "Gender", field: "gender" },
      { title: "Rating", field: "rating", formatter: "star", hozAlign: "center", width: 100 },
      { title: "Favourite Color", field: "col" },
      { title: "Date Of Birth", field: "dob", hozAlign: "center", sorter: "date" },
      { title: "Driver", field: "car", hozAlign: "center", formatter: "tickCross" },
    ],
    data: tabledata,

    groupUpdateOnCellEdit: true, //单元格编辑后重新分组当前行
  });

  const table_group2 = new Tabulator("#table-group2", {
    layout: "fitColumns",
    groupBy: ["gender", "col"],
    groupStartOpen: [true, false],
    groupValues: [false, ["red", "blue", "green"]],
    groupToggleElement: "header",
    columns: [
      { title: "Name", field: "name", width: 200 },
      { title: "Progress", field: "progress", sorter: "number" },
      { title: "Gender", field: "gender" },
      { title: "Rating", field: "rating", formatter: "star", hozAlign: "center", width: 100 },
      { title: "Favourite Color", field: "col" },
      { title: "Date Of Birth", field: "dob", hozAlign: "center", sorter: "date" },
      { title: "Driver", field: "car", hozAlign: "center", formatter: "tickCross" },
    ],
    data: tabledata,
  });

  // table.setGroupBy("gender");//设置分组
  // table.setGroupBy(false); //清除分组
  // table.setGroupValues([["male", "female", "smizmar"]]);//设置允许分组的值
  // table.setGroupStartOpen(true);//设置分组打开状态
</script>
<script>
  const data_tree = [
    {
      name: "Oli Bob",
      location: "United Kingdom",
      gender: "male",
      col: "red",
      dob: "14/04/1984",
      _children: [
        { name: "Mary May", location: "Germany", gender: "female", col: "blue", dob: "14/05/1982" },
        { name: "Christine Lobowski", location: "France", gender: "female", col: "green", dob: "22/05/1982" },
        {
          name: "Brendon Philips",
          location: "USA",
          gender: "male",
          col: "orange",
          dob: "01/08/1980",
          _children: [
            { name: "Margret Marmajuke", location: "Canada", gender: "female", col: "yellow", dob: "31/01/1999" },
            { name: "Frank Harbours", location: "Russia", gender: "male", col: "red", dob: "12/05/1966" },
          ],
        },
      ],
    },
    { name: "Jamie Newhart", location: "India", gender: "male", col: "green", dob: "14/05/1985" },
    {
      name: "Gemma Jane",
      location: "China",
      gender: "female",
      col: "red",
      dob: "22/05/1982",
      _children: [{ name: "Emily Sykes", location: "South Korea", gender: "female", col: "maroon", dob: "11/11/1970" }],
    },
    { name: "James Newman", location: "Japan", gender: "male", col: "red", dob: "22/03/1998" },
  ];

  const table_tree = new Tabulator("#table-tree", {
    height: "350px",
    layout: "fitColumns",
    data: data_tree,
    dataTree: true,
    dataTreeStartExpanded: true,
    columns: [
      { title: "Name", field: "name", responsive: 0 }, //never hide this column
      { title: "Location", field: "location" },
      { title: "Gender", field: "gender", responsive: 2 }, //hide this column first
      { title: "Favourite Color", field: "col" },
      { title: "Date Of Birth", field: "dob", hozAlign: "center", sorter: "date" },
    ],
  });
</script>

 

 

标签:false,name,title,js,field,table,tabulator,true,好用
From: https://www.cnblogs.com/caroline2016/p/18428329

相关文章

  • js DOM学习的综合样例
    jsDOM学习的综合样例本人简单学习了一点md语法,写出来的博客会更好看喵.样例介绍主要实现利用DOM的获取标签对象的功能和对监听功能实现三个功能:(1)开灯,关灯(2)对标签进行全选,反选(3)对文本框聚焦时字母为大写,反之为小写基本实现方法(1)开灯关灯:a.......
  • DC00013基于jsp servlet javabeen鲜花销售管理系统网上花店含配套报告
    1、项目功能演示DC00013基于jsp+servlet+javabeen鲜花销售管理系统网上花店网站鲜花销售网上花店管理系统2、项目功能描述 基于jsp+servlet+javabeen鲜花销售管理系统分为用户和系统管理员两个角色。2.1用户功能1、系统登录、系统注册2、主页、产品信息、联系我们3......
  • JS的链判断符有几种写法,有哪些用法?
    你好,我是沐爸,欢迎点赞、收藏、评论和关注。在ES6之前如何判断一个对象深层嵌套的属性?ES6的链判断符又是怎么简化操作的呢?它有几种写法?带着这三个问题,我们一起看一看。ES6之前在ES6之前的JS中,如果读取对象内部的某个属性,往往需要判断一下,属性的上层对象是否存在。......
  • 基于jsp的图书馆管理系统的设计与实现 (含源码+sql+视频导入教程+文档)
    ......
  • C# json格式化
    //格式化JsonprivatestringConvertStringToJson(stringstr){//格式化json字符串JsonSerializerserializer=newJsonSerializer();TextReadertr=newStringReader(str);JsonTextReaderj......
  • 【已解决】ElementPlus 的 el-menu 组件如何用 js 控制展开某个子菜单,并在其他组件中
    文章目录需求几次探索官网寻找线索(解决办法)需求我如何用代码来实现ElementPlus的菜单的展开和收缩呢?几次探索尝试通过找到节点之后,使用click事件,失败了//伪代码如下consthandleFindNodeAndClick=()=>{console.log('handleFindNodeAndClick');......
  • jsp蛋糕甜品商城系统72lo6
    jsp蛋糕甜品商城系统72lo6本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表项目功能用户,商品分类,商品信息开题报告内容一、项目背景与意义随着电子商务的蓬勃发展,线上购物已成为人们日常生活中不可或缺的......
  • jsp蛋糕甜品店管理系统4fx6j
    jsp蛋糕甜品店管理系统4fx6j本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表项目功能用户,商品分类,商品尺寸,商品信息开题报告内容一、立题背景与意义随着互联网的普及和消费者购物习惯的改变,线上购物已......
  • jsp蛋糕商城系统6b4n8
    jsp蛋糕商城系统本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表项目功能用户,商品分类,商品信息开题报告内容一、立题依据随着互联网技术的飞速发展,电子商务已成为现代商业活动的重要组成部分。蛋糕作为一......
  • jsp单重病患者复诊与跟踪管理系统87o39
    jsp单重病患者复诊与跟踪管理系本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表项目功能患者病历,医生,科室,医院信息,复诊记录,用户技术要求:   开发语言:JSP前端使用:HTML5,CSS,JSP动态网页技术后端使......