GridExporter

Ext.ns('Ext.ux.grid');

/**
 * Plugin (ptype = 'gridexporter') that adds export functionality for the grid.
 * 
 * @class Ext.ux.grid.GridExporter
 * @extends Ext.util.Observable
 * @author 
 * @version $Id: GridExporter.js 21171 2010-03-19 06:33:11Z $
 * @ptype gridexporter
 */
Ext.ux.grid.GridExporter = Ext.extend(Ext.util.Observable, {

  mode : 'local', // 'relay','remote'

  mask : true,

  confirmExportRows : 1000,

  maxExportRows : 0,

  maskMsg : '导出中,请稍候……',

  constructor : function(config) {
    Ext.apply(this, config);

    this.addEvents(
    /**
     * @event beforeexport
     */
    'beforeexport',
    /**
     * @event export
     */
    'export',
    /**
     * @event exportexception
     */
    'exportexception');

    Ext.ux.grid.GridExporter.superclass.constructor.call(this);
  },

  init : function(grid) {
    this.grid = grid;

    Ext.apply(grid, {
      exportCsv : this.exportCsv.createDelegate(this),
      exportExcel : this.exportExcel.createDelegate(this),
      exportPdf : this.exportPdf.createDelegate(this)
    });
  },

  buildColumns : function(cm) {
    var columns = [];
    for ( var i = 0; i < cm.getColumnCount(); i++) {
      if (!(cm.isHidden(i) || cm.getColumnId(i) == 'numberer' || cm.getColumnId(i) == 'checker')) {
        var col = {
          header : cm.getColumnHeader(i),
          dataIndex : cm.getDataIndex(i),
          width : cm.getColumnWidth(i)
        }
        columns.push(col);
      }
    }
    return columns;
  },

  buildData : function(store, cm) {
    var data = [];

    for ( var j = 0, len = store.getCount(); j < len; j++) {
      var rec = store.getAt(j);
      var row = {};
      for ( var i = 0; i < cm.getColumnCount(); i++) {
        if (!(cm.isHidden(i) || cm.getColumnId(i) == 'numberer' || cm.getColumnId(i) == 'checker')) {
          var renderer = cm.getRenderer(i);
          var name = cm.getDataIndex(i);
          var value = rec.data[name];
          var p = {};
          try {
            value = renderer.call(cm.config[i], value, p, rec, j, i, store);
          } catch (err) {

          }
          if (typeof value === 'string') {
            value = value.replace(/<[^>]*>/g, '');
          }
          row[name] = value;
        }
      }
      data.push(row);
    }
    return data;
  },

  submitAsTarget : function(submitCfg) {
    var opt = submitCfg || {}, D = document;

    var form = opt.form || Ext.DomHelper.append(D.body, {
      tag : 'form',
      cls : 'x-hidden'
    });

    form = Ext.getDom(form.form || form, D);

    form.target = opt.target || '_self';
    form.method = opt.method || 'POST';
    form.action = opt.url || Ext.ux.grid.GridExporter.PATH;
    opt.encoding && (form.enctype = form.encoding = String(opt.encoding));

    var hiddens, hd;
    if (opt.params) {
      hiddens = [];
      var ps = typeof opt.params == 'string' ? Ext.urlDecode(params, false) : opt.params;
      for ( var k in ps) {
        if (ps.hasOwnProperty(k)) {
          hd = D.createElement('input');
          hd.type = 'hidden';
          hd.name = k;
          hd.value = ps[k];
          form.appendChild(hd);
          hiddens.push(hd);
        }
      }
    }
    (function() {
      form.submit();
      hiddens && Ext.each(hiddens, Ext.removeNode, Ext);
      Ext.fly(form, '_dynaForm').hasClass('x-hidden') && Ext.removeNode(form);
      this.grid.bwrap.unmask();
      this.fireEvent('export', this, submitCfg);
    }).defer(100, this);
  },

  exportGrid : function(exportCfg) {
    var opt = exportCfg || {};
    var grid = this.grid;
    if (grid && grid.getStore() && grid.getStore().getCount() > 0) {
      var confirmExportRows = opt.confirmExportRows || this.confirmExportRows || 0;
      var totalCount = grid.getStore().getTotalCount();
      if ((confirmExportRows > 0) && (totalCount > confirmExportRows)) {
        Ext.Msg.confirm('导出数量太多', '导出数量超过' + confirmExportRows + '条记录,可能导致速度缓慢。<br>是否终止导出,重新设置查询范围以减少导出数量?', function(btn, text) {
          if (btn == 'no') {
            return this.doExport(exportCfg);
          } else {
            return false;
          }
        }, this);
      } else {
        return this.doExport(exportCfg);
      }

    } else {
      Ext.Msg.alert('无法导出', '没有需要导出的数据');
      return false;
    }
  },

  doExport : function(exportCfg) {
    var opt = exportCfg || {};
    var maxExportRows = opt.maxExportRows || this.maxExportRows || 0;
    var totalCount = this.grid.getStore().getTotalCount();
    if ((maxExportRows > 0) && (totalCount > maxExportRows)) {
      Ext.Msg.confirm('导出数据限制', '只导出前' + maxExportRows + '条记录,是否继续?', function(btn, text) {
        if (btn == 'yes') {
          return this.exportData(exportCfg);
        } else {
          return false;
        }
      }, this);
    } else {
      return this.exportData(exportCfg);
    }

  },

  exportData : function(exportCfg) {
    var opt = exportCfg || {};
    var grid = this.grid;

    this.fireEvent('beforeexport', this, exportCfg);
    if (this.mask) {
      grid.bwrap.mask(this.maskMsg);
    }
    var mode = opt.mode || this.mode || 'local';
    var store = grid.getStore();

    var maxExportRows = opt.maxExportRows || this.maxExportRows || 0;
    var cm = grid.getColumnModel();
    var params = {
      format : opt.format || 'csv',
      filename : opt.filename || grid.title || 'export',
      columns : opt.columns || Ext.encode(this.buildColumns(cm)),
      maxExportRows : maxExportRows
    };
    if (mode == 'local') {
      params.data = Ext.encode(this.buildData(store, cm));
      this.submitAsTarget( {
        params : params
      });

    } else if (mode == 'remote') {
      params.remoteMethod = opt.remoteMethod || this.remoteMethod;
      var lastOptions = store.lastOptions || {};
      var p = lastOptions.params || {};
      if (p.dwrFunctionArgs) {
        p = p.dwrFunctionArgs[0];
      } else {
        p = Ext.apply( {}, p, store.baseParams);
      }
      p = opt.params || p || {};
      params.params = Ext.encode(p);
      this.submitAsTarget( {
        params : params
      });
    } else {
      if (!this.exportStore) {
        this.exportStore = new store.constructor( {
          proxy : store.proxy,
          reader : store.reader,
          listeners : {
            scope : this,
            load : function(ds, recs, opts) {
              params.data = Ext.encode(this.buildData(ds, cm));
              this.submitAsTarget( {
                params : params
              });
              ds.removeAll();
            },
            loadexception : function() {
              this.fireEvent('exportexception', this);
            }
          }
        });

      }

      var lastOptions = Ext.apply( {}, store.lastOptions, {
        params : {}
      });
      lastOptions.params.start = 0;
      lastOptions.params.limit = maxExportRows;
      if (lastOptions.params.dwrFunctionArgs) {
        lastOptions.params.dwrFunctionArgs[1] = 0;
        lastOptions.params.dwrFunctionArgs[2] = maxExportRows;
      }
      this.exportStore.load(lastOptions);
    }
  },

  exportPdf : function() {
    this.exportGrid( {
      format : "pdf"
    });
  },
  exportExcel : function() {
    this.exportGrid( {
      format : "excel"
    });
  },
  exportCsv : function() {
    this.exportGrid( {
      format : "csv"
    });
  },

  destroy : function() {
    if (this.exportStore) {
      Ext.destroy(this.exportStore);
    }
  }

});
if (Ext.version >= 3) {
  Ext.preg('gridexporter', Ext.ux.grid.GridExporter);
}
Ext.ux.grid.GridExporter.PATH = '/export.do';

你可能感兴趣的:(ext,Excel,J#)