52,797
社区成员
发帖
与我相关
我的任务
分享
/*
*功能:直接由Ext的grid生成Excel
*注意: 只支持IE
*参数:param1: gridId
* param2: sheetName
*/
Ext.downExcel= function(config){
//Ext.Excel.superclass.constructor.call(this, config);
Ext.apply(this,config);
};
Ext.apply(Ext.downExcel.prototype,{
extGridToExcel : function(){
if (!Ext.isIE) {
Ext.Msg.alert('Error','你的浏览器不支持!');
return;
}
try{
if(Ext.getCmp(this.gridId)){
/********************************************* grid 生成 Excel ***************************************/
var oXL = new ActiveXObject("Excel.Application");
var oWB = oXL.Workbooks.Add();
var oSheet = oWB.ActiveSheet;
var grid = Ext.getCmp(this.gridId);
var store = grid.getStore();
var recordCount = store.getCount();
var view = grid.getView();
var cm = grid.getColumnModel();
var colCount = cm.getColumnCount();
var temp_obj = [];
//去掉隐藏的列
for(var i = 0; i < colCount;i++){
if(cm.isHidden(i)){
}else{
temp_obj.push(i);
}
}
oSheet.Cells(1,1).value =this.sheetName;;
//得到表头
for(var i = 1; i <= temp_obj.length;i++){
oSheet.Cells(2,i).value = cm.getColumnHeader(temp_obj[i - 1]);
}
//写入数据
for(var i = 1 ; i <= recordCount; i++){
for(var j = 1; j<= temp_obj.length; j++){
//设置单元格格式为字符串
oSheet.Cells(i+2,j).NumberFormat = '@';
oSheet.Cells(i+2,j).value = view.getCell(i-1,temp_obj[j-1]).innerText;
}
}
if(this.sheetName){
oSheet.Name = this.sheetName;
}
oXL.UserControl = true;
oXL.Visible = true;
}else{
Ext.Msg.alert('Error','明细数据grid没有创建成功!');
return;
}
}catch(e){
if(Ext){
Ext.Msg.show({
title:'提示',
msg:'请设置IE的菜单\'工具\'->Internet选项->安全->自定义级别->\'对未标记为可安全执行脚本ActiveX控件初始化并执行脚本\'->选择[启用] 就可以生成Excel',
buttons:Ext.Msg.OK,
icon:Ext.Msg.INFO
});
}else{
alert('不支持ExtJs框架');
return;
}
}
}
});
使用
//导出grid数据到excel
exportToExcel : function() {
var excel = new Ext.downExcel({
gridId : this.id,
sheetName : this.title
});
excel.extGridToExcel();
}
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=\"xxxx.xls\"");
Response.Write("生成的内容字符串");