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

[复制链接]
查看8664 | 回复0 | 2024-8-29 19:44:37 | 显示全部楼层 |阅读模式
一、简介
6 U$ V$ y2 F- }7 X0 ^& X; e+ {: \/ |, t6 ?* |0 Z
1 F* A* j1 |5 ]0 R+ B2 @9 E
前端表格在线编辑组件:Ag-Grid 入门使用教程案例分享-1.jpg

7 ^, |+ ?2 f% q2 ^) q基本认知
$ t8 a5 P$ d; X6 N ag-Grid 是一个功能强大、灵活且高性能的用于构建数据表格(Data Grid)的 JavaScript 库。它提供了丰富的功能和选项,使开发人员能够轻松地创建复杂的数据表格,并支持大量数据的展示和操作。* X' X. @+ [6 m% }& C9 \2 x
主要特点】: i8 ~6 K  M3 I$ g9 o

    3 p( e# p* r8 n9 K8 ~2 a
  • 灵活性:ag-Grid 提供了丰富的功能和配置选项,开发人员可以根据需求定制数据表格的外观和行为,包括列定义、排序、筛选、分组、汇总等。' N$ @5 z0 N  H% ^
  • 高性能:ag-Grid 采用虚拟滚动技术,能够有效处理大量数据的展示和操作,保持高性能的同时提供流畅的用户体验。, V* h7 `$ d7 ^  S  P/ m  Y0 b
  • 跨平台支持:ag-Grid 可以在多种前端框架(如 Angular、React、Vue 等)和多种环境(如浏览器、移动端应用)中使用,具有很好的跨平台兼容性。
    8 V8 [. Q6 X+ Z# ~, T: B% y, }+ {
  • 丰富的 API 和事件:ag-Grid 提供了丰富的 API 和事件,开发人员可以通过编程方式控制数据表格的行为,并响应用户操作。
    8 X$ [& n  |7 D$ D( ]
  • 社区支持:ag-Grid 拥有活跃的社区,提供了广泛的文档、示例和支持,帮助开发人员快速上手并解决问题。
    6 b6 b! o; y2 k$ ?; U
- T# L9 o5 R* V* Y7 \. B

7 M" e( v3 E# e6 B5 @二、详细使用3 k: o* M5 ]8 O
  a/ M; N% K9 B+ ], c) [
【1】简单基本功能演示6 M% v0 O: c0 r4 B% |

* n- l: Q; M4 ~9 i0 E! `& n! \0 r! X& M5 ]& a3 ?9 s
: A7 F/ h3 N6 U, S8 M$ K' H
提供功能如下:① 数据列表展示;② 数据编辑;③ 默认全字段可排序;④ 设置默认列属性;& A' u* _. O  _& o7 r
<!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>
$ L3 M/ p, T! L) W5 r
0 [1 @+ x9 I* J9 s' B& \
前端表格在线编辑组件:Ag-Grid 入门使用教程案例分享-2.jpg
, o) w! ]% _7 J; ?: E; m
【2】核心:表格基本功能实例展示% ~% `( t# ?) Y4 h+ y
  Y9 Z" t- g) t* `' {
此案例演示主要功能如下:【基本内容参照:JavaScript Grid: Quick Start | AG Grid示例实现】, j0 @5 |. _, X8 X1 w, ?& f

    9 i- b3 Q2 b$ y$ t  z
  • 表格是否可以编辑;✅
    : B- L: f; M) \& D; E& C
  • 默认指定排序;✅ 默认按照Make字段降序排列. f( e# m3 _$ `+ M- l
  • 单元格列样式 & 行样式;✅
    3 T$ Q! \  i* ?
  • 文本格式化;✅(见价格列)
    : S* w! Z' I- i2 C0 ]8 W
  • 初始咧宽度;✅(见价格列)
    9 c  j$ Z& ^. Y9 ]
  • 组合两列数据;✅(Make&Model)& ]* l( j/ T. \- E" V* ]
  • 每列增加操作按钮;✅Button列- p2 J: T9 I. {5 q" |: S( W
  • 全局列属性定义;✅defaultColDef 配置
    ' h% n  i7 N- x8 C
  • 分页属性设置;✅$ X% L/ z$ v/ @) q0 p
  • 多选框;✅
    - x$ f) ]% I- l) E' Q% \4 W  e
完整代码演示如下:
" n6 j" ^9 M& c* {" Z* W" H<!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>实现效果代码展示:
# }. [$ s  a7 @/ X, y  x- y, O2 U5 p  b
前端表格在线编辑组件:Ag-Grid 入门使用教程案例分享-3.jpg

( D& J5 \$ M& z$ {1 I2 j( u动态演示图如下:$ O' E- }6 j. Y% M. G
$ S' h! X6 O6 K  `0 v6 O/ ~9 x( _
前端表格在线编辑组件:Ag-Grid 入门使用教程案例分享-4.jpg
0 E0 o( B' N- Z  u7 F/ Q
【3】数据导出/ b) @4 ]6 q1 s
  i# Z' }  o3 }( K) W) r, C
官方示例:JavaScript Example - Csv Export - Csv Export& N( \; J9 Z7 f* ?& |
完整代码展示:$ T' d. @4 I. e0 `$ S
<!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>页面效果展示:
1 L) @* D: A3 v' G8 w! }: C2 z/ x& |* ]2 F  o3 R
前端表格在线编辑组件:Ag-Grid 入门使用教程案例分享-5.jpg
% v( q1 O) I1 q7 |2 {: X% u
【4】数据导入
% |5 [* F+ `: a0 A8 K0 `# F% q8 ^" I, C" g" s8 K! x+ F+ v  H
见 官网案例 【JavaScript Grid: Excel Import | AG Grid】。; j3 b0 ^7 x& h; t+ S/ B4 O/ u
附录
9 z* _5 z$ q& Z5 C1 Z7 h. m' n" }. w! r
    5 D' m7 S* O5 F3 S3 S- a. b. v
  • 官网地址:AG Grid: High-Performance React Grid, Angular Grid, JavaScript Grid
    ( j- Z; K! k5 A* N; u
  • 官网地址(JavaScript 版本):JavaScript Grid: Quick Start | AG Grid
    $ s6 r4 b8 l( [# C% B; H+ C
  • 官方案例:Demo - Performance Grid
    4 E% O" S# x- O5 \0 I& _5 @
  • 官方主题:AG Grid Theme Builder
    0 d2 f& G- U7 U: ^6 g% }+ N% F
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

288

金钱

0

收听

0

听众
性别
保密

新手上路

金钱
288 元