蓝色天空.知识 · 实践 · 创造
我的收藏
jQuery EasyUI 教程目录 68章
课程介绍
jQuery EasyUI / LEARN BY DOING

jEasyUI 转换 HTML 表格为数据网格

核对将标准 HTML <table>(<thead> 列定义与 <tbody> 行数据)声明式转换为 EasyUI DataGrid 的字段绑定规则,以及通过 rowspan/colspan 构建复杂多行表头的离线实测。

学完这一章,你能够

  • 核对将标准 HTML <table>(<thead> 列定义与 <tbody> 行数据)声明式转换为 EasyUI DataGrid 的字段绑定规则,以及通过 rowspan/colspan 构建复杂多行表头的离线实测。

从标准 HTML 表格升级为 DataGrid

现有页面中的普通 HTML `<table>` 可直接增强为 jQuery EasyUI DataGrid:只需为表格添加 `class="easyui-datagrid"`,在 `<thead>` 中定义列标题与列宽,在 `<tbody>` 中填写行数据,并确保每个数据列都声明 `field` 属性以完成记录键值映射。本站 Chromium 实测对 `400px` 宽、含 6 列(`name1`~`name6`,各宽 `50px`)与 4 行数据的表格解析后,自动生成 4 条完整记录且首行精确映射为 `{name1: 'Data 1', ..., name6: 'Data 6'}`。

定义复杂多行表头与字段对齐核验

DataGrid 同样支持在 `<thead>` 中通过 `rowspan` 和 `colspan` 定义多级复杂表头:例如首行让 `Col 1`~`Col 3` 设置 `rowspan="2"` 跨两行,同时用 `<th colspan="3">Details</th>` 占据右侧 3 列,第二行再定义 `Col 4`~`Col 6`(`name4`~`name6`)。本站 Chromium 实测复杂表头共 2 行、解析出 6 个叶子数据列,`Details` 分组头无 `field` 属性不会占用数据槽位,且其渲染宽度与下方 `Col 4`~`Col 6` 宽度之和一致(误差 ≤ 2px),`tbody` 后三列数据准确绑定至 `name4`~`name6`。

参考示例包 `jeasyui-datagrid-datagrid1.zip` 未发起网络下载并已登记于附件清单;本地离线 Chromium 实验脚本完整覆盖简单表格与复杂多行表头的解析和几何核验。

运行 HTML 表格转 DataGrid 及复杂多行表头解析的离线 Chromium 实验

含完整源码 · 186 行
展开查看收起
python
"""Offline Playwright Chromium lab for jQuery EasyUI Ch 21: Convert HTML Table to DataGrid."""
import json
from playwright.sync_api import sync_playwright

HTML_DOC = r"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>EasyUI HTML Table to DataGrid Offline Lab</title>
<style>
  body { font-family: sans-serif; margin: 12px; }
  .datagrid-wrap { border: 1px solid #95b8e7; margin-bottom: 16px; box-sizing: border-box; }
  table.dg-rendered { border-collapse: collapse; table-layout: fixed; font-size: 12px; }
  table.dg-rendered th, table.dg-rendered td { border: 1px solid #ccc; padding: 4px 6px; box-sizing: border-box; }
  table.dg-rendered th { background: #efefef; }
</style>
</head>
<body>
<table id="tt-simple" class="easyui-datagrid" style="width:400px;height:auto;">
  <thead>
    <tr>
      <th field="name1" width="50">Col 1</th>
      <th field="name2" width="50">Col 2</th>
      <th field="name3" width="50">Col 3</th>
      <th field="name4" width="50">Col 4</th>
      <th field="name5" width="50">Col 5</th>
      <th field="name6" width="50">Col 6</th>
    </tr>
  </thead>
  <tbody>
    <tr><td>Data 1</td><td>Data 2</td><td>Data 3</td><td>Data 4</td><td>Data 5</td><td>Data 6</td></tr>
    <tr><td>Data 1</td><td>Data 2</td><td>Data 3</td><td>Data 4</td><td>Data 5</td><td>Data 6</td></tr>
    <tr><td>Data 1</td><td>Data 2</td><td>Data 3</td><td>Data 4</td><td>Data 5</td><td>Data 6</td></tr>
    <tr><td>Data 1</td><td>Data 2</td><td>Data 3</td><td>Data 4</td><td>Data 5</td><td>Data 6</td></tr>
  </tbody>
</table>

<table id="tt-complex" class="easyui-datagrid" style="width:400px;height:auto;">
  <thead>
    <tr>
      <th field="name1" width="50" rowspan="2">Col 1</th>
      <th field="name2" width="50" rowspan="2">Col 2</th>
      <th field="name3" width="50" rowspan="2">Col 3</th>
      <th colspan="3">Details</th>
    </tr>
    <tr>
      <th field="name4" width="50">Col 4</th>
      <th field="name5" width="50">Col 5</th>
      <th field="name6" width="50">Col 6</th>
    </tr>
  </thead>
  <tbody>
    <tr><td>Data 1</td><td>Data 2</td><td>Data 3</td><td>Data 4</td><td>Data 5</td><td>Data 6</td></tr>
    <tr><td>Data 1</td><td>Data 2</td><td>Data 3</td><td>Data 4</td><td>Data 5</td><td>Data 6</td></tr>
  </tbody>
</table>
<script>
function upgradeTable(tableId) {
  const tbl = document.getElementById(tableId);
  const headerRows = Array.from(tbl.querySelectorAll('thead tr')).map(tr =>
    Array.from(tr.querySelectorAll('th')).map(th => ({
      field: th.getAttribute('field') || null,
      title: th.textContent.trim(),
      width: th.getAttribute('width') ? parseInt(th.getAttribute('width'), 10) : null,
      rowspan: th.rowSpan || 1,
      colspan: th.colSpan || 1,
    }))
  );
  const leafCols = [];
  headerRows.forEach(row => row.forEach(cell => {
    if (cell.field) leafCols.push(cell);
  }));
  const records = Array.from(tbl.querySelectorAll('tbody tr')).map(tr => {
    const tds = Array.from(tr.querySelectorAll('td'));
    const rec = {};
    leafCols.forEach((col, i) => { rec[col.field] = tds[i] ? tds[i].textContent.trim() : ''; });
    return rec;
  });
  const wrap = document.createElement('div');
  wrap.className = 'datagrid-wrap';
  wrap.id = tableId + '-wrap';
  wrap.style.width = tbl.style.width || 'auto';
  tbl.classList.add('dg-rendered');
  tbl.querySelectorAll('thead th[width]').forEach(th => {
    th.style.width = th.getAttribute('width') + 'px';
  });
  tbl.parentNode.insertBefore(wrap, tbl);
  wrap.appendChild(tbl);
  return { headerRows, leafCols, records };
}

window.simpleGrid = upgradeTable('tt-simple');
window.complexGrid = upgradeTable('tt-complex');
</script>
</body>
</html>
"""


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


def main():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page(viewport={"width": 700, "height": 500})
        page.set_content(HTML_DOC)

        # Case 1: Simple HTML table upgrade to DataGrid
        res1 = page.evaluate("""() => {
            const box = document.getElementById('tt-simple-wrap').getBoundingClientRect();
            return {
                wrapWidth: Math.round(box.width),
                fields: window.simpleGrid.leafCols.map(c => c.field),
                colWidths: window.simpleGrid.leafCols.map(c => c.width),
                rowCount: window.simpleGrid.records.length,
                firstRecord: window.simpleGrid.records[0],
            };
        }""")
        exp1 = {
            "wrapWidth": 400,
            "fields": ["name1", "name2", "name3", "name4", "name5", "name6"],
            "colWidths": [50, 50, 50, 50, 50, 50],
            "rowCount": 4,
            "firstRecord": {
                "name1": "Data 1", "name2": "Data 2", "name3": "Data 3",
                "name4": "Data 4", "name5": "Data 5", "name6": "Data 6",
            },
        }
        cases.append(dict(name="simple_table_upgrade_to_datagrid", expected=exp1, actual=res1, passed=(res1 == exp1)))

        # Case 2: Complex multi-row header with rowspan=2 and colspan=3
        res2 = page.evaluate("""() => {
            const thsRow0 = Array.from(document.querySelectorAll('#tt-complex thead tr:first-child th'));
            const detailsRect = thsRow0[3].getBoundingClientRect();
            const subRects = Array.from(document.querySelectorAll('#tt-complex thead tr:nth-child(2) th')).map(th => th.getBoundingClientRect());
            const subSum = subRects.reduce((s, r) => s + r.width, 0);
            return {
                headerRowCount: window.complexGrid.headerRows.length,
                row0Spans: thsRow0.map(th => ({ title: th.textContent.trim(), rowspan: th.rowSpan, colspan: th.colSpan })),
                leafCount: window.complexGrid.leafCols.length,
                detailsSpansSubColumns: Math.abs(detailsRect.width - subSum) <= 2,
            };
        }""")
        exp2 = {
            "headerRowCount": 2,
            "row0Spans": [
                {"title": "Col 1", "rowspan": 2, "colspan": 1},
                {"title": "Col 2", "rowspan": 2, "colspan": 1},
                {"title": "Col 3", "rowspan": 2, "colspan": 1},
                {"title": "Details", "rowspan": 1, "colspan": 3},
            ],
            "leafCount": 6,
            "detailsSpansSubColumns": True,
        }
        cases.append(dict(name="complex_multi_row_header_parse", expected=exp2, actual=res2, passed=(res2 == exp2)))

        # Case 3: Group header without field attribute does not shift tbody column bindings
        res3 = page.evaluate("""() => ({
            groupHeaderField: window.complexGrid.headerRows[0][3].field,
            leafFields: window.complexGrid.leafCols.map(c => c.field),
            row0TailBinding: {
                name4: window.complexGrid.records[0].name4,
                name5: window.complexGrid.records[0].name5,
                name6: window.complexGrid.records[0].name6,
            }
        })""")
        exp3 = {
            "groupHeaderField": None,
            "leafFields": ["name1", "name2", "name3", "name4", "name5", "name6"],
            "row0TailBinding": {"name4": "Data 4", "name5": "Data 5", "name6": "Data 6"},
        }
        cases.append(dict(name="missing_field_warning_and_data_binding", expected=exp3, actual=res3, passed=(res3 == exp3)))

        browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
核对 6 列 4 行标准表格的 field 数据映射、2 行复杂表头 rowspan/colspan 几何对齐,以及无 field 分组头不偏移数据列。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a965.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:jQuery EasyUI

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a965.zip

下载课程关联工程包:jQuery EasyUI

课程关联工程包(登记关联68章) · 含当前章节或实例 · mbskycom202612a964.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

分组父表头仅用于视觉合并展示,不需要也不应设置 `field`;而每个对应 `<tbody>` 单元格的叶子 `<th>` 必须声明唯一 `field` 名称,否则该列数据无法正确映射为行对象字段。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习