前端表格在线编辑组件:Ag-Grid 入门使用教程案例分享

[复制链接]
查看8688 | 回复0 | 2024-8-29 19:44:37 | 显示全部楼层 |阅读模式
一、简介
$ M& O2 ?0 P% y1 x7 a3 u; |- K. a* O; |1 |$ V7 F2 @
$ Q5 _0 ]" W6 f5 j0 G
前端表格在线编辑组件:Ag-Grid 入门使用教程案例分享-1.jpg

+ k  {8 f3 r2 T; S2 c3 ~8 y基本认知
0 e: u3 u+ d3 j6 f  i! p% E ag-Grid 是一个功能强大、灵活且高性能的用于构建数据表格(Data Grid)的 JavaScript 库。它提供了丰富的功能和选项,使开发人员能够轻松地创建复杂的数据表格,并支持大量数据的展示和操作。9 [/ Q' g+ K* q+ F8 R& v: a
主要特点】
( `8 f$ K. a( q. `% Z
    9 R7 L! _. G9 l1 {( _
  • 灵活性:ag-Grid 提供了丰富的功能和配置选项,开发人员可以根据需求定制数据表格的外观和行为,包括列定义、排序、筛选、分组、汇总等。
    - Q9 h* @8 [5 f8 Z; X
  • 高性能:ag-Grid 采用虚拟滚动技术,能够有效处理大量数据的展示和操作,保持高性能的同时提供流畅的用户体验。
    3 U2 p. ?% b5 m& X) t2 a* I
  • 跨平台支持:ag-Grid 可以在多种前端框架(如 Angular、React、Vue 等)和多种环境(如浏览器、移动端应用)中使用,具有很好的跨平台兼容性。& d. @. W0 y- |' z
  • 丰富的 API 和事件:ag-Grid 提供了丰富的 API 和事件,开发人员可以通过编程方式控制数据表格的行为,并响应用户操作。
    . I7 `+ P& N" F, ~$ Z9 ?
  • 社区支持:ag-Grid 拥有活跃的社区,提供了广泛的文档、示例和支持,帮助开发人员快速上手并解决问题。
    ' ]- K! K( g- j' g

/ U, C0 ?: W1 U1 @
9 F8 G4 v; g% B- \6 z& z9 g二、详细使用, g1 I, k" t- H6 B# O; P" ?) b- Z
5 K1 X5 }! ], H* X7 K$ x& f! {& `! V
【1】简单基本功能演示7 Q% Y; C! U) T! J  N
1 x; D) p5 k$ J6 T' H

/ r5 o/ r, e0 d. z: q
  {5 A' E4 o) M$ S提供功能如下:① 数据列表展示;② 数据编辑;③ 默认全字段可排序;④ 设置默认列属性;
$ ^2 ]" b  k+ Y; p4 Z' p' \<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Ag-Grid Simple Example</title>        <link rel="stylesheet" href="https://unpkg.com/ag-grid-community/dist/styles/ag-grid.css">        <link rel="stylesheet" href="https://unpkg.com/ag-grid-community/dist/styles/ag-theme-alpine.css">        <!-- Includes all JS & CSS for the JavaScript Data Grid -->        <script src="https://cdn.jsdelivr.net/npm/ag-grid-community/dist/ag-grid-community.min.js"></script>        <!-- <script src="https://unpkg.com/ag-grid-community/dist/ag-grid-community.min.noStyle.js"></script> -->        <!-- <script src="https://unpkg.com/ag-grid-enterprise"></script> --></head><body>    <div id="myGrid" class="ag-theme-alpine" style="height: 200px; width: 600px;"></div>    <script >                document.addEventListener('DOMContentLoaded', function() {                    var gridOptions = {                        columnDefs: [                            { headerName: "Make", field: "make", editable: true },                            { headerName: "Model", field: "model", editable: true },                            { headerName: "Price", field: "price", editable: true }                        ],                        rowData: [                            { make: "Toyota", model: "Celica", price: 35000 },                            { make: "Ford", model: "Mondeo", price: 32000 },                            { make: "Porsche", model: "Boxster", price: 72000 }                        ],                        defaultColDef: {                            flex: 1,                            minWidth: 100,                            editable: true                        }                    };                                    var gridDiv = document.querySelector('#myGrid');                    new agGrid.Grid(gridDiv, gridOptions);                });        </script></body></html>: A% w  ]! \" _" [
  e) Q; J1 _- L) J7 w" N" Y% n
前端表格在线编辑组件:Ag-Grid 入门使用教程案例分享-2.jpg
. n9 b) o. h0 \% x
【2】核心:表格基本功能实例展示: M5 T3 e% N, T+ h8 x& K9 d

+ N+ H, i: j1 y+ z此案例演示主要功能如下:【基本内容参照:JavaScript Grid: Quick Start | AG Grid示例实现】) D9 M& a* j1 ~6 H' `4 n

    * Q; z9 R% F5 `2 P. b# M9 n0 r
  • 表格是否可以编辑;✅) c6 W" c7 q7 K% z( D. g% F- T$ ~3 A
  • 默认指定排序;✅ 默认按照Make字段降序排列9 T# F  y4 K5 l. B1 G- X
  • 单元格列样式 & 行样式;✅
    & C* Q' u2 a% X
  • 文本格式化;✅(见价格列)" U  o% Y$ F4 h3 z
  • 初始咧宽度;✅(见价格列)
      u- L' E9 [8 R8 D6 [" b9 }  M
  • 组合两列数据;✅(Make&Model)
    & K9 e- V' h/ ?7 z
  • 每列增加操作按钮;✅Button列! v) E  S% E% t8 `
  • 全局列属性定义;✅defaultColDef 配置' D+ m6 ?6 L( _
  • 分页属性设置;✅: z; N- D% |% q7 ?- U
  • 多选框;✅; A8 I: Y0 ?& H4 i6 J7 D
完整代码演示如下:3 M  p) e- j1 G
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Ag-Grid Simple Example</title>        <!-- Includes all JS & CSS for the JavaScript Data Grid -->        <script src="https://cdn.jsdelivr.net/npm/ag-grid-community/dist/ag-grid-community.min.js"></script>        <!--          学习内容:         1.表格是否可以编辑;✅         2.默认指定排序;✅ 默认按照Make字段降序排列         3.单元格列样式 & 行样式;✅         4.文本格式化;✅(见价格列)         5.初始咧宽度;✅(见价格列)         6.组合两列数据;✅(Make&Model)         7.每列增加操作按钮;✅Button列         8.全局列属性定义;✅defaultColDef 配置         9.分页属性设置;✅         10.多选框;✅         -->         <style type="text/css">                 .rag-green {                   background-color: #33cc3344;                 }                .rag-red {                  background-color: #cc222244;                }         </style></head><body>    <div id="myGrid" class="ag-theme-alpine" style="height: 225px; width: 1000px;"></div>    <script >                let gridApi;                                class CustomButtonComponent {                  eGui;                  eButton;                  eventListener;                                  init() {                    this.eGui = document.createElement("div");                    let eButton = document.createElement("button");                    eButton.className = "btn-simple";                    eButton.textContent = "点击弹窗!";                    this.eventListener = () => alert("clicked");                    eButton.addEventListener("click", this.eventListener);                    this.eGui.appendChild(eButton);                  }                                  getGui() {                    return this.eGui;                  }                                  refresh() {                    return true;                  }                                  destroy() {                    if (this.eButton) {                      this.eButton.removeEventListener("click", this.eventListener);                    }                  }                }                                // 自定义排序函数                function dateComparator(date1, date2) {                  const date1Number = monthToComparableNumber(date1);                  const date2Number = monthToComparableNumber(date2);                                  if (date1Number === null && date2Number === null) {                    return 0;                  }                  if (date1Number === null) {                    return -1;                  }                  if (date2Number === null) {                    return 1;                  }                                  return date1Number - date2Number;                }                                // eg 29/08/2004 gets converted to 20040829                function monthToComparableNumber(date) {                  if (date === undefined || date === null || date.length !== 10) {                    return null;                  }                  const yearNumber = Number.parseInt(date.substring(6, 10));                  const monthNumber = Number.parseInt(date.substring(3, 5));                  const dayNumber = Number.parseInt(date.substring(0, 2));                                  return yearNumber * 10000 + monthNumber * 100 + dayNumber;                }                                // 【核心功能】                document.addEventListener('DOMContentLoaded', function() {                        var gridOptions = {                           // 分页start                                pagination: true,                                paginationPageSize: 3,                                paginationPageSizeSelector: [3, 6, 10],                           // 分页end                           // 行样式 start                           rowClassRules: {                                   // apply red to Ford cars                                   'rag-red': params => params.data.make === 'Ford',                           },                           // 行样式 end                           // 多选 start                                rowSelection: 'multiple',                           // 多选 end(记住每列需要配置 多选属性)                        columnDefs: [                            { headerName: "Make", field: "make", editable: true , sort:"desc", checkboxSelection: true, flex:2},                            { headerName: "Model", field: "model", editable: true,  cellClassRules: {                                                        // apply green to electric cars                                                        'rag-green': params => params.value === "Celica",                                                }                                         },                            { headerName: "默认值列", valueGetter: p=> "默认值", flex: 2 /*相对宽度*/},                            { headerName: "Make & Model", valueGetter: p=> p.data.make + "  " + p.data.model, flex: 2 /*相对宽度*/},                            { headerName: "Price", field: "price", editable: true, valueFormatter: p => '$ ' + p.value.toLocaleString() ,flex:2 },                            { headerName: "Electric", field: "electric", editable: false },                                        { field: "year", width: 120, unSortIcon: true },                                        { field: "date", comparator: dateComparator },                                        { headerName: "操作按钮",field: "button", cellRenderer: CustomButtonComponent, flex: 1 },                        ],                        rowData: [                            { make: "Toyota", model: "Celica", price: 358000 , electric: true, year: 2021, date: "1/10/2021"},                            { make: "Ford", model: "Mondeo", price: 32000 , electric: false, year: 2021, date: "10/10/2021"},                            { make: "Porsche", model: "Boxster", price: 72000 ,  electric: true, year: 2021, date: "1/11/2021"},                            { make: "Porsche", model: "Boxster", price: 72000 ,  electric: true, year: 2019, date: "1/10/2019"},                                        { make: "Toyota", model: "Celica", price: 358000 , electric: true, year: 2021, date: "1/10/2021"},                                        { make: "Ford", model: "Mondeo", price: 32000 , electric: false, year: 2023, date: "1/10/2023"},                                        { make: "Toyota", model: "Celica", price: 358000 , electric: true, year: 2021, date: "15/10/2021"},                                        { make: "Ford", model: "Mondeo", price: 32000 , electric: false, year: 2001, date: "1/10/2001"},                        ],                        defaultColDef: {                            flex: 1,                            minWidth: 100,                            editable: true                        }                    };                                    var gridDiv = document.querySelector('#myGrid');                    // gridApi = new agGrid.Grid(gridDiv, gridOptions);                        gridApi = agGrid.createGrid(gridDiv, gridOptions);                                                });        </script></body></html>实现效果代码展示:
  g2 ^$ Y4 ]- h& s6 P: c  d3 |6 N# N; {# e* A
前端表格在线编辑组件:Ag-Grid 入门使用教程案例分享-3.jpg
7 q$ ]8 K$ i( d: l$ O3 x. f
动态演示图如下:
1 O/ x( W/ S2 Q$ `4 ?8 F4 m3 y; ]# _5 ~; i, [5 u4 i# K
前端表格在线编辑组件:Ag-Grid 入门使用教程案例分享-4.jpg

3 n) X  |0 D" A2 q- u【3】数据导出
+ L1 `' X/ R  c0 X0 w6 G- H5 Z3 ^3 [. I0 `+ h: h# v; m
官方示例:JavaScript Example - Csv Export - Csv Export
6 U" }. p4 w  k: C- h完整代码展示:2 q* K- G% \/ W" A- Y- L! P; q
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Ag-Grid Simple Example</title>        <!-- Includes all JS & CSS for the JavaScript Data Grid -->        <script src="https://cdn.jsdelivr.net/npm/ag-grid-community/dist/ag-grid-community.min.js"></script>        <style>            button {                display: inline-block;                font-weight: bold;            }        </style></head><body>    <div id="myGrid" class="ag-theme-alpine" style="height: 200px; width: 600px;"></div>                <div style="display: flex; flex-direction: column; height: 100%">            <div style="margin: 10px 0">                <button onclick="onBtnUpdate()">Show CSV export content text</button>                <button onclick="onBtnExport()">Download CSV export file</button>            </div>            <div style="flex: 1 1 0; position: relative; display: flex; flex-direction: row; gap: 20px">                <div id="gridContainer" style="flex: 1">                    <div id="myGrid" style="height: 100%; display: block; flex: 1" class="ag-theme-quartz"></div>                </div>                            </div>                                <div>                        <textarea rows="8" cols="85"                            id="csvResult"                            style="flex: 1"                            placeholder="Click the Show CSV export content button to view exported CSV here"                        ></textarea>                </div>        </div>            <script >                        let gridApi;                                                const gridOptions = {                          defaultColDef: {                            editable: true,                            minWidth: 100,                            flex: 1,                          },                                                  suppressExcelExport: true,                          popupParent: document.body,                                                  columnDefs: [{ field: "make" }, { field: "model" }, { field: "price" }],                                                  rowData: [                            { make: "Toyota", model: "Celica", price: 35000 },                            { make: "Ford", model: "Mondeo", price: 32000 },                            { make: "Porsche", model: "Boxster", price: 72000 },                          ],                        };                                                function onBtnExport() {                          gridApi.exportDataAsCsv();                        }                                                function onBtnUpdate() {                          document.querySelector("#csvResult").value = gridApi.getDataAsCsv();                        }                                                // setup the grid after the page has finished loading                        document.addEventListener("DOMContentLoaded", function () {                          var gridDiv = document.querySelector("#myGrid");                          gridApi = agGrid.createGrid(gridDiv, gridOptions);                        });        </script></body></html>页面效果展示:8 j. p8 h0 q* l; j
# `  u2 f! V) ~0 |, v
前端表格在线编辑组件:Ag-Grid 入门使用教程案例分享-5.jpg
1 X) b% v8 T; P) C. T
【4】数据导入
3 N9 O9 M: g" Y' T& d. l
& q7 @4 O+ t) ?( ]$ I# Q4 C) d见 官网案例 【JavaScript Grid: Excel Import | AG Grid】。$ Y6 d1 m% Q" F$ x0 [
附录. X& K* ~: E: g9 v0 c
# ]) P1 a7 L5 r8 F4 _
    - T: V: @$ i/ P5 H; ?/ F) g* W
  • 官网地址:AG Grid: High-Performance React Grid, Angular Grid, JavaScript Grid
    ; X" q7 {' Z2 N! f# q
  • 官网地址(JavaScript 版本):JavaScript Grid: Quick Start | AG Grid. F0 L1 \6 K: ^
  • 官方案例:Demo - Performance Grid
    7 o9 @% P; u7 H8 r8 J
  • 官方主题:AG Grid Theme Builder/ h# n# T4 z% D8 D9 |
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

290

金钱

0

收听

0

听众
性别
保密

新手上路

金钱
290 元