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'}
    ]  
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM