extjs4动态生成多表头

目前使用的方法,google了好久+自己研究出来的,通过json生成表头

效果图:

View Code
  1 Ext.onReady(function () {
  2     //header也就是你应该从后台取回的表头数据,现在写死在了这里
  3     //var grid;
  4     Ext.Ajax.request({
  5         params: {
  6             parafdno: '',
  7             parafcy: '',
  8             pararepnum: ''
  9         }, //发送的参数
 10         url: "../BLL/H_yus/H_pinpdpfyysBLL.ashx?action=tlist", //请求的地址
 11         success: function (response, option) {
 12             //alert("rsptest:" + response.responseText);
 13             var forminfo = Ext.decode(response.responseText);
 14             //var forminfo = [{ name: 'company', header: 'Company' }, { name: 'price', header: 'Price' }, { name: 'change', header: 'change'}]
 15             Ext.define('model', {
 16                 extend: 'Ext.data.Model',
 17                 fields: forminfo.fields,
 18                 validations: [{//满足该条件才会提交
 19                     type: 'length',
 20                     field: 'bennfpxse',
 21                     min: 1
 22                 }]
 23             });
 24             var store = Ext.create('Ext.data.Store', {
 25                 //autoDestroy: true,
 26                 autoLoad: false,
 27                 autoSync: true,
 28                 model: 'model',
 29                 proxy: {
 30                     type: 'ajax',
 31                     //url: 'H_cuxfaBLL.ashx?action=list',
 32                     api: {
 33                         read: '../BLL/H_yus/H_pinprwfjBLL.ashx?action=read',
 34                         create: '../BLL/H_yus/H_pinprwfjBLL.ashx?action=create',
 35                         update: '../BLL/H_yus/H_pinprwfjBLL.ashx?action=update',
 36                         destroy: '../BLL/H_yus/H_pinprwfjBLL.ashx?action=destory'
 37                     },
 38                     extraParams: {
 39                         'parafcy': '',
 40                         'parafdno': '',
 41                         'pararepnum': ''
 42                     },
 43                     reader: {
 44                         type: 'json',
 45                         successProperty: 'success', //判断是否成功时的返回标题
 46                         root: 'items', //根目录
 47                         messageProperty: 'Msg'//返回的错误信息等其他信息的标题
 48                     },
 49                     writer: {
 50                         type: 'json',
 51                         //writeAllFields: false,
 52                         encode: true,
 53                         root: 'items', //将提交行的数据易json格式传递到后台
 54                         allowSingle: false
 55                     },
 56                     listeners: {
 57                         exception: function (proxy, response, operation) {
 58                             Ext.MessageBox.show({
 59                                 title: 'REMOTE EXCEPTION',
 60                                 msg: operation.getError(),
 61                                 icon: Ext.MessageBox.ERROR,
 62                                 buttons: Ext.Msg.OK
 63                             });
 64                         }
 65                     }
 66                 }
 67             });
 68             //alert(forminfo.columns);
 69             var columns = [];
 70             var coms = [];
 71             Ext.each(forminfo.columns, function (s) {
 72                 //alert(s);
 73                 coms.push({
 74                     header: s.header,
 75                     dataIndex: s.name
 76                 });
 77             });
 78             Ext.define('grid', {
 79                 extend: 'Ext.grid.Panel',
 80                 store: store,
 81                 alias: 'widget.writergrid',
 82                 height: 300,
 83                 requires: ['Ext.grid.plugin.CellEditing', 'Ext.form.field.Text', 'Ext.toolbar.TextItem'],
 84 
 85                 initComponent: function () {
 86 
 87                     this.editing = Ext.create('Ext.grid.plugin.CellEditing');
 88 
 89                     Ext.apply(this, {
 90                         iconCls: 'icon-grid',
 91                         frame: true,
 92                         defaultType: 'textfield',
 93                         viewConfig: { loadMask: new Ext.LoadMask(this, { msg: '正在加载数据...' }) },
 94                         plugins: [this.editing],
 95                         dockedItems: [{
 96                             xtype: 'toolbar',
 97                             items: [{
 98                                 iconCls: 'icon-add',
 99                                 icon: '../Scripts/img/add.gif',
100                                 text: '加行',
101                                 disabled: false,
102                                 scope: this,
103                                 handler: this.onAddClick
104                             }, {
105                                 iconCls: 'icon-delete',
106                                 icon: '../Scripts/img/delete.gif',
107                                 text: '减行',
108                                 disabled: true,
109                                 itemId: 'delete',
110                                 scope: this,
111                                 handler: this.onDeleteClick
112                             }]
113                         }],
114                         columns: forminfo.columns
115                     });
116                     this.callParent();
117                     this.getSelectionModel().on('selectionchange', this.onSelectChange, this);
118                 },
119 
120                 onSelectChange: function (selModel, selections) {
121                     this.down('#delete').setDisabled(selections.length === 0);
122                     selections = this.getView().getSelectionModel().getSelection()[0];
123                 },
124 
125                 onSync: function () {
126                     this.store.sync();
127                 },
128 
129                 onDeleteClick: function () {
130                     var selection = this.getView().getSelectionModel().getSelection()[0];
131                     if (selection) {
132                         this.store.remove(selection);
133                     }
134                 },
135 
136                 onAddClick: function () {
137                     var rec = new model({
138                         shangpbm: '',
139                         shangpmc: '',
140                         guig: '',
141                         fenl: 0,
142                         fenlnew: 0
143                     }),
144                      edit = this.editing;
145                     //this.store.reload();
146                     edit.cancelEdit();
147                     this.store.insert(0, rec);
148                     edit.startEditByPosition({
149                         row: 0,
150                         column: 0
151                     });
152                     //alert(rec);
153                 }
154 
155             });
156 
157             initform();
158             //grid.render('form-ct');
159         }
160     });
161 
162 });

传过来的json格式

JSON格式
{
  "columns ": [
    {
      "dataIndex ": "shangpbm ",
      "header ": "商品编码 ",
      "field ": {
        "xtype ": "textfield "
      }
    },
    {
      "dataIndex ": "shangpmc ",
      "header ": "商品名称 ",
      "align ": "center ",
      "field ": {
        "xtype ": "textfield "
      }
    },
    {
      "text ": "02-02品牌部费用-人员费用 ",
      "columns ": [
        {
          "dataIndex ": "02020004 ",
          "header ": "品牌人员工资 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "02020005 ",
          "header ": "品牌人员费用 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "02020006 ",
          "header ": "后勤人员费用 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "02020039 ",
          "header ": "品牌人员招待费 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        }
      ]
    },
    {
      "text ": "02-03品牌部费用-预留费用 ",
      "columns ": [
        {
          "dataIndex ": "02030007 ",
          "header ": "预留费用1 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "02030008 ",
          "header ": "预留费用2 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        }
      ]
    },
    {
      "text ": "03-04销售部费用-管理费用 ",
      "columns ": [
        {
          "dataIndex ": "03040009 ",
          "header ": "管理人员工资 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "03040010 ",
          "header ": "管理人员绩效奖金 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "03040011 ",
          "header ": "管理人员住宿费 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "03040012 ",
          "header ": "管理人员通讯费 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "03040013 ",
          "header ": "管理人员汽车费 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "03040014 ",
          "header ": "管理人员差旅费 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "03040015 ",
          "header ": "业务人员工资 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "03040016 ",
          "header ": "业务人员绩效奖金 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "03040017 ",
          "header ": "业务人员住宿费 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "03040018 ",
          "header ": "业务人员通讯费 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "03040019 ",
          "header ": "业务人员汽车费 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "03040020 ",
          "header ": "业务人员差旅费 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "03040021 ",
          "header ": "促销人员工资 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "03040022 ",
          "header ": "促销人员奖金提成 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "03040023 ",
          "header ": "业务招待费 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "03040024 ",
          "header ": "业务用酒费 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "03040025 ",
          "header ": "办公费 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "03040038 ",
          "header ": "办公租赁费 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        }
      ]
    },
    {
      "text ": "03-05销售部费用-市场费用 ",
      "columns ": [
        {
          "dataIndex ": "03050026 ",
          "header ": "终端补助 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "03050027 ",
          "header ": "终端包装 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "03050028 ",
          "header ": "终端促销 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "03050029 ",
          "header ": "终端促销品 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "03050030 ",
          "header ": "终端拉动 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "03050031 ",
          "header ": "销售返利1 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "03050032 ",
          "header ": "销售返利2 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "03050033 ",
          "header ": "流通促销 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "03050034 ",
          "header ": "流通促销品 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "03050035 ",
          "header ": "流通包装 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "03050036 ",
          "header ": "商超费用 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        },
        {
          "dataIndex ": "03050037 ",
          "header ": "商超促销 ",
          "field ": {
            "xtype ": "numberfield ",
            "minValue ": "0 "
          }
        }
      ]
    }
  ],
  "fields ": [
    {
      "name ": "shangpbm "
    },
    {
      "name ": "shangpmc "
    },
    {
      "name ": "02020004 "
    },
    {
      "name ": "02020005 "
    },
    {
      "name ": "02020006 "
    },
    {
      "name ": "02020039 "
    },
    {
      "name ": "02030007 "
    },
    {
      "name ": "02030008 "
    },
    {
      "name ": "03040009 "
    },
    {
      "name ": "03040010 "
    },
    {
      "name ": "03040011 "
    },
    {
      "name ": "03040012 "
    },
    {
      "name ": "03040013 "
    },
    {
      "name ": "03040014 "
    },
    {
      "name ": "03040015 "
    },
    {
      "name ": "03040016 "
    },
    {
      "name ": "03040017 "
    },
    {
      "name ": "03040018 "
    },
    {
      "name ": "03040019 "
    },
    {
      "name ": "03040020 "
    },
    {
      "name ": "03040021 "
    },
    {
      "name ": "03040022 "
    },
    {
      "name ": "03040023 "
    },
    {
      "name ": "03040024 "
    },
    {
      "name ": "03040025 "
    },
    {
      "name ": "03040038 "
    },
    {
      "name ": "03050026 "
    },
    {
      "name ": "03050027 "
    },
    {
      "name ": "03050028 "
    },
    {
      "name ": "03050029 "
    },
    {
      "name ": "03050030 "
    },
    {
      "name ": "03050031 "
    },
    {
      "name ": "03050032 "
    },
    {
      "name ": "03050033 "
    },
    {
      "name ": "03050034 "
    },
    {
      "name ": "03050035 "
    },
    {
      "name ": "03050036 "
    },
    {
      "name ": "03050037 "
    }
  ]
}

附加个json.net的写法

json.net
        JObject jo = new JObject{
            new JProperty("columns",new JArray(
                new JObject{
                    new JProperty("dataIndex","shangpbm"),
                    new JProperty("header","商品编码"),
                    new JProperty("field",new JObject{
                        new JProperty("xtype","textfield")
                    })
                },
                new JObject{
                    new JProperty("dataIndex","shangpmc"),
                    new JProperty("header","商品名称"),
                    //new JProperty("width","320"),
                    new JProperty("align","center"),
                    new JProperty("field",new JObject{
                        new JProperty("xtype","textfield")
                    })
                },
                from p in dth.AsEnumerable()
                select new JObject{
                    new JProperty("text",p["A1"].ToString()+p["A2"].ToString()),
                    new JProperty("columns",new JArray(
                        from q in dt.AsEnumerable()
                        where q["A1"].ToString()==p["A1"].ToString()
                        select new JObject{
                            new JProperty("dataIndex",q["ZACCTYP_0"]),
                            new JProperty("header",q["ZACCDES_0"]),
                            new JProperty("field",new JObject{
                                new JProperty("xtype","numberfield"),
                                new JProperty("minValue","0")
                            })
                        }
                        )
                    )
                }
            )),
            new JProperty("fields",new JArray(
                new JObject{
                    new JProperty("name","shangpbm")
                },
                new JObject{
                    new JProperty("name","shangpmc")
                },
                from q in dt.AsEnumerable()
                select new JObject{
                    new JProperty("name",q["ZACCTYP_0"])
                }
            ))
        };

 

还有一个看到的似乎也异曲同工

http://blog.csdn.net/myairen1365/article/details/8197977

View Code
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <title>动态生成表格</title>
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">
        <link rel="stylesheet" type="text/css"
            href="ext4/resources/css/ext-all.css">
        <script type="text/javascript" src="ext4/bootstrap.js"></script>
        <script type="text/javascript" src="ext4/ext-all.js"></script>
        <script type="text/javascript" src="ext4/locale/ext-lang-zh_CN.js"></script>

        <script type="text/javascript">
    Ext.onReady(function() {

        var json_f;
        Ext.Ajax.request({//store对象在创建时需要制定fields属性,因此使用ajax首先从后台获得列名
            url : 'json/testUser!testPage.action', //从action返回的response中读取数据,也可以从其他地方获取数据 
            method : 'POST',
            async : false,
            success : function(response) {
                //将返回的结果转换为json对象,注意extjs4中decode函数已经变成了:Ext.JSON.decode

                s = response.responseText;
                json_f = Ext.JSON.decode(response.responseText); //获得后台传递json 

            }
        });
        var thePageSize = 5;

        //JSON数据源,此处创建了带有分页功能的store数据源
        var humresStore = Ext.create('Ext.data.Store', {
            pageSize : thePageSize,
            fields : json_f.fields,//根据上面的ajax从后台action动态获得

            proxy : {
                type : 'ajax',
                url : 'json/testUser!testPage.action',//获取数据的url
                method : 'POST',
                reader : {
                    type : 'json',
                    root : 'data',
                    totalProperty : 'totalRecord'//json数据,表示分页数据总数
                }
            },

            sorters : [ {
                property : 'id',
                direction : 'DESC'
            } ]
        });

        humresStore.load({
            params : {
                start : 0,
                limit : thePageSize
            }
        });

        //创建表格,可以加入更多的属性。
        Ext.create("Ext.grid.Panel", {
            title : '动态表格~~~~~~~~~~~',
            width : 400,
            height : 300,
            id : 'configGrid',
            name : 'configGrid',
            columns : [], //注意此行代码,至关重要
            displayInfo : true,
            emptyMsg : "没有数据显示",
            renderTo : 'grid',//渲染到页面
            forceFit : true,
            dockedItems : [ {
                xtype : 'pagingtoolbar',
                store : humresStore,
                dock : 'bottom',
                displayInfo : true,
                //displayMsg: '显示第 {0} 条到 {1} 条记录 / 共 {2} 条',
                emptyMsg : "没有记录!"
            } ]
        });

        //通过ajax获取表头以及表格数据
        Ext.Ajax
                .request({
                    url : 'json/testUser!testPage.action', //从json文件中读取数据,也可以从其他地方获取数据 
                    method : 'POST',
                    success : function(response) {
                        //将返回的结果转换为json对象,注意extjs4中decode函数已经变成了:Ext.JSON.decode
                        
                        var json = Ext.JSON.decode(response.responseText); //获得后台传递json
                        
                        //根据store和column构造表格
                        Ext.getCmp("configGrid").reconfigure(humresStore,
                                json.columns);
                        
                    }
                });

    })
</script>
    </head>

    <body>
        <!-- 将表格渲染在此处 -->
        <div id="grid"></div>
    </body>
</html>

还一个本来打算弄不出来的时候试试,后来没用着

http://253405050.iteye.com/blog/1330734

1.创建DynamicGrid.js

JS代码
Ext.define('Ext.grid.DynamicGrid',{
    extend : 'Ext.grid.Panel',
    
    alias : 'widget.dynamicgrid',
    
    initComponent : function() {
        var me = this;

        var store = Ext.create('Ext.data.JsonStore', {
            fields: [],
            pageSize: 5,
            proxy: {
                type: 'ajax',
                url : 'data.js',
                reader: {
                    type: 'json',
                    root: 'recordList',
                    totalProperty : 'recordCount'
                }
            }
        });
        
        var headerCtCfg = {
            items: [],
            border: me.border
        };
        
        me.columns = headerCtCfg.items;
        
        me.headerCt = Ext.create('Ext.grid.header.Container', headerCtCfg);

        this.bindStore(store);
        this.bbar.bindStore(this.store, true);
        
        this.callParent();
    },
    
    onRender: function(ct, position) {
        this.store.on('load', function(store, records) {
            var jsonData = store.proxy.reader.jsonData;
            
            if (typeof(jsonData.columns) === 'object') {
                var columns = [];
                
                if (this.rowNumberer) {
                    columns.push(new Ext.grid.RowNumberer());
                }
                
                if (this.checkboxSelModel) {
                    this.selModel = new Ext.selection.CheckboxModel();
                }
                
                Ext.each(jsonData.columns, function(column) {
                    columns.push(column);
                });
                
                var store = Ext.create('Ext.data.Store', {
                    fields : jsonData.fields,
                    data : jsonData.recordList
                });
                
                this.reconfigure(store, columns);
                this.render();
            }
        }, this);
        
        this.store.load();
        
        Ext.grid.DynamicGrid.superclass.onRender.call(this, ct, position);
    }
});

2.创建grid

View Code
var dynamicGrid = Ext.create('Ext.grid.DynamicGrid', {
        title: '测试动态列',
        renderTo: 'dynamic-grid',
        storeUrl: 'data.json',
        width : 600,
        height: 300,
        store: store,
        rowNumberer: true,
        checkboxSelModel: false,
        bodyStyle: 'padding-top: 22px',    //不知道什么原因,列头会把第一行给覆盖,所以需要加上这个样式
        bbar : new Ext.PagingToolbar({
            store: store,
            pageSize: 5,
            displayInfo: true,
            displayMsg: '显示第{0}到{1}条数据,共{2}条',
            emptyMsg: "没有数据",
            beforePageText: "第",
            afterPageText: '页 共{0}页'
        })  
    });

返回的数据格式:

json格式
{  
    'fields': [  
        {'name': 'id', 'type': 'int'},  
        {'name': 'name', 'type': 'string'},  
        {'name': 'sex', 'type': 'boolean'}
    ],
    'success': true,  
    'recordCount': 50,  
    'recordList': [  
        {'id': '1', 'name': 'AAA', sex: 1},  
        {'id': '2', 'name': 'BBB', sex: 1},  
        {'id': '3', 'name': 'CCC', sex: 0},  
        {'id': '4', 'name': 'DDD', sex: 1},  
        {'id': '5', 'name': 'EEE', sex: 1}
    ],  
    'columns': [  
        {'header': 'ID', 'dataIndex': 'id'},  
        {'header': 'User', 'dataIndex': 'name'},  
        {'header': 'SEX', 'dataIndex': 'sex'}
    ]  
}

 

posted @ 2012-12-05 20:02  玢棂  阅读(3531)  评论(0编辑  收藏  举报