Ext.onReady(function() {
var store = new Ext.data.JsonStore({
fields : [ 'name' ]
});
var sm = new Ext.grid.CheckboxSelectionModel({ singleSelect : true });
var editorGridPanel = new Ext.grid.EditorGridPanel({
id : 'editorGridPanel',
region:"center",
store:store,
sm : sm,
colModel : new Ext.grid.ColumnModel({
defaults : { width : 100, sortable : true, resizable : true },
columns : [
new Ext.grid.CheckboxSelectionModel({ singleSelect : true }),
new Ext.grid.RowNumberer(),
{ header : "姓名", dataIndex : "name", editor : new Ext.form.TextField({ allowBlank : false })}
]
}),
viewConfig:{ forceFit: true },
listeners : {
celldblclick : cellDblClick,
afteredit : afterEdit
}
});
new Ext.Viewport({
layout : 'border',
items : [ editorGridPanel ]
});
});
Ext.onReady(function() {
var editorGridPanel = Ext.getCmp("editorGridPanel");
editorGridPanel.getStore().insert(0, new Ext.data.Record({ name : ""}));
});
function cellDblClick(grid, rowIndex, columnIndex, e) {
//看了EditorGridPanel的源码,双击事件调用的方法是startEditing,但是是在celldblclick事件调用的方法后,此时EditorGridPanel中的文本框还没初始化
//所以不能增加文本框的Ctrl+V或者右键粘贴事件,也就不能截获粘贴板中的内容,所以这里手动的调用startEditing来生成文本框
grid.startEditing(rowIndex, columnIndex);
//得到活动单元格的编辑器
var activeEditor = grid.activeEditor;
//得到DOM元素
var element = activeEditor.getEl();
//得到inputs框
var inputs = element.dom.getElementsByTagName("INPUT");
if(inputs.length>0){
//先将之前的时间全部释放
inputs[0].detachEvent("onbeforepaste", onBeforePaste);
//注册粘贴前事件
inputs[0].attachEvent("onbeforepaste", onBeforePaste);
//阻止默认粘贴
inputs[0].attachEvent("onpaste", function(){return false;})
}
//return false是因为要阻止调用默认的双击事件的方法
return false;
}
function onBeforePaste(event){
var editorGridPanel = Ext.getCmp("editorGridPanel");
var record = editorGridPanel.getSelectionModel().getSelected();
var rowIndex = editorGridPanel.getStore().indexOf(record);
var count = editorGridPanel.getStore().getCount();
//得到粘贴板内容
var text = window.clipboardData.getData("Text");
//得到粘贴板内容的数组
var textArray = text.split("\n");
if(textArray.length>0){
//从excel 复制的数据最后一行会有空的回车符,这里要手动的去掉
if(textArray[textArray.length-1].length==0){
textArray.splice(textArray.length-1,1);
}
for(var i=0;i<textArray.length;i++){
var editorGridPanel = Ext.getCmp("editorGridPanel");
//如果需要粘贴的行大于EditorGridPanel已经存在的行,则插入新行数据,否则更新数据
if(rowIndex+i>=count){
editorGridPanel.getStore().insert(rowIndex+i, new Ext.data.Record({ name : textArray[i]}));
}else{
var currentRecord = editorGridPanel.getStore().getAt(rowIndex+i);
currentRecord.set("name", textArray[i]);
}
}
}
editorGridPanel.stopEditing(true);
//触发afteredit事件,在最后插入一个新行
editorGridPanel.fireEvent("afteredit", null);
event.returnValue=false ;
}
/**
* 结束编辑后判断最后一行是否为空,如果不为空,插入一行空白行
*/
function afterEdit(){
var store = Ext.getCmp("editorGridPanel").getStore();
var lastRecord = store.getAt(store.getCount()-1);
if(lastRecord.get("name").length>0){
store.insert(store.getCount(), new Ext.data.Record({ name : ""}))
}
}
PS:此功能只适用于IE,并且会弹出是否允许访问剪切板的对话框