java ext excel导入导出

来源:互联网 发布:c语言中\0是什么意思 编辑:程序博客网 时间:2024/05/17 06:41

EXTJS4上传文件或EXCEL批量导入源码 

2012-03-03 14:33:22|  分类:EXTJS4知识 |  标签:|字号订阅

■  前台FORM
Ext.require(['Ext.form.field.File']);
//whbmemo:因为父窗口中已经有高级查询表单,故为了避免冲突,表单域都不再设置id
Ext.define('AP.view.WinImportView', {
extend : 'Ext.window.Window',
alias : 'widget.winimportview',
width : 450,
height : 260,
layout : 'fit',
resizable : true,
frame : false,
modal : true,
border : false,
bodyBorder : false,
items : [{//items_win_begin
  border : false,
  bodyBorder : false,
  id:'formimport',
  xtype : 'form', 
  frame: true,
  fileUpload:true,
  layout: 'anchor',
        defaults: {
            anchor: '100%'
        },
        bodyPadding: 5,
        fieldDefaults: {
            labelAlign: 'right',          
            msgTarget : 'side'
        },
  items: [//item_form_begin
  {
   xtype: 'fieldset',
   collapsible: true,
   title: 'Excel导入',
   defaultType: 'textfield',
   layout: 'anchor',
   defaults: {
    anchor: '100%'
   },
   items: [{//item_fieldset1_begin
    xtype: 'container',
    layout : {
     type : 'table',//内部容器用表格风格排版
     columns : 1,
     bodyStyle : 'padding:0 0 0 0'
    },
                defaultType: 'textfield',           
    items: [//item_container_begin   
    {
     xtype: 'filefield',
              name: 'file',
              fieldLabel: '请选择Excel文件',
              width:400,           
              allowBlank: false,                       
              buttonText: ' 浏 览 ',
              buttonConfig: {
                  //iconCls: 'upload-icon'
              } 
    },
    {
     width:400,
     html:'<a href='+Qas.getAppName() + '/template/Excel/ApImportTemplate.xls> 模板文件下载 </a>[提示:只有按照模板格式整理Excel表,才允许导入数据]'        
    },
    {
     xtype:'panel',
     frame:true,
     autoScroll:true,   
     height:120,
     width:400,         
     name:'resultmsg',
     id:'resultmsg',
     html:''//在后台动态更改    
    }     
   ]//item_container_end 
  }]//item_fieldset1_end
}]//item_form_END
}],//items_win_end
dockedItems : [ {
  xtype : 'toolbar',
  dock : 'bottom',
  items : [ '->', {
   xtype : 'button',
   text : '上传文件并导入数据',
   iconCls : 'save',
   action: 'upload',
   scale : 'small'
  },{
   xtype : 'button',
   text : '取消',
   iconCls : 'cancel',
   handler : function(m, e) {
    this.ownerCt.ownerCt.close();
   }
  }]
}]//dockedItems结束
});

■  中间CONTROL层
"winimportview button[action=upload]":{
     click: function(sm, selections,a,c){       
      var form=Ext.getCmp("formimport");                
      if (form.getForm().isValid()) {
        //重置信息提示框
        Ext.getCmp("resultmsg").body.update("正在导入数据,请稍候...");
       form.getForm().submit({
                       url:  Qas.getAppName() + '/ap_import_ext.html',
                       method : 'POST',                                            
                       waitTitle:'请等待...',
                       waitMsg: '正在上传Excel文件,分析导入数据,请稍候...',                    
                       success : function(form,action) {                  
                        console.log("ServerJson="+action.response.responseText);
                        Ext.getCmp("resultmsg").body.update(action.result.msg);                                                                                                       
           },
           failure : function(form, action){//一般是HTTP500内部错误
            console.log("ServerJson="+action.response.responseText);
                        Ext.getCmp("resultmsg").body.update(action.result.msg);                  
                     }
                   });
                  }                     
     }
    },
■  后台Action层
(1)如果是上传文件:
/*
String uploadDir = "";
String fileName="";  
try {
//自己指定一个上传路径
uploadDir = ServletActionContext.getServletContext().getRealPath("/admin/Excel/"); 
//为了防止后台文件名重复,一般不采用真实文件名,而是随机命名  
//随机数重命名机制,可替换时间戳机制
String random = StringUtil.getRandom(3, 1000);     
fileName = random + new Date().getTime() + ".xls";  
log.debug(uploadDir  +"/"+ fileName);
//注意:如果想获取真正的前台文件名称,可以从前台表单加1个hidden传过来  
File savedir = new File(uploadDir);
//如果不存在相关目录,先创建一个
if (!savedir.exists()) {
  savedir.mkdirs();
}
//创建输入流接收前台文件
InputStream stream = new FileInputStream(file);
//创建输出流保存后台文件
OutputStream bos = new FileOutputStream(uploadDir +"/"+ fileName);
int bytesRead;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
  bos.write(buffer, 0, bytesRead);
}
bos.close();
stream.close();
result=true;
msg=uploadDir  +"/"+ fileName+" success";
log.debug(msg); 

} catch (Exception e) {
result=false;
e.printStackTrace();
}
*/
(2)如果是EXCEL批量导入
//WHB:EXCEL批量导入,throws IOException是必须的
public void ap_import_ext() throws IOException {
  log.debug("################## 打印所有变量_begin");
  Enumeration rnames = getRequest().getParameterNames();
  for (Enumeration e = rnames; e.hasMoreElements();) {
   String thisName = e.nextElement().toString();
   String thisValue = getRequest().getParameter(thisName);
   log.debug(thisName + "-------" + thisValue);
  }
  log.debug("################## 打印所有变量_end"); 
 
  //默认保存失败
  Boolean result=false;
  String msg = "Excel文件分析失败,请参照模板文件整理数据!";  

  try {
   //whb:excel批量导入时,不一定非要先保存,可以直接分析
   //创建输入流接收前台数据
   InputStream stream = new FileInputStream(file);  
   Workbook wk = Workbook.getWorkbook(stream);
   Sheet sheet = wk.getSheet(0);  
   // 说明:getCell(1,0)方法,1代表列,0代表行
   log.debug("EXCEL第0列,第0行的数据为:"+sheet.getCell(0, 0).getContents().trim());  
   //定义2个临时数组和4个临时变量  
   List<String> macList=new ArrayList();
   List<String> locationList=new ArrayList();
   String tempLocation="";
   String tempMac="";
   Integer succCount=0;
   Integer emptyCount=0;  
   //WHB:第0行为标题行,从第1行开始分析
   for (int i = 1; i < sheet.getRows(); i++) {
    tempLocation = sheet.getCell(0, i).getContents().trim();// 取热点名称
    tempMac=sheet.getCell(2, i).getContents().trim();// 取Mac地址
    //只有热点名称和MAC同时不为空才允许导入
    if(tempLocation=="" && tempMac==""){
     emptyCount++;
     continue;
    }else{
     //首先检查MAC是否重复
     if(apManager.getApByMac(tempMac)!=null){
      macList.add(tempMac);
      continue;
     }    
     Location location=locationManager.getLocationByName(tempLocation);
     //再次检查热点名称是否合法
     if(location==null){
      locationList.add(tempLocation);
      continue;
     }
     //查询并保存区域信息
     ap=new Ap();
     provinceId = location.getProvinceId();    
    
     //导入AP数据    
     apManager.saveAp(ap);    
     succCount++;
    }
   
   }  
   wk.close();   
   stream.close();
  
   result=true;
   msg="Excel文件导入结果信息汇总:<br>(1)导入成功的记录数为:"+succCount
   +"<br>(2)因热点名称和MAC地址都为空,导入失败的记录数为:"+emptyCount
   +"<br>(3)因MAC地址数据库中已经存在,导入失败的记录数为:"+macList.size()
   +"<br>(4)因热点名称数据库中并不存在,导入失败的记录数为:"+locationList.size()
   +" <br>错误MAC地址如下:"+macList.toString()
   +" <br>错误热点信息如下:"+locationList.toString();
   log.debug(result);
   log.debug(msg);
  } catch (Exception e) {
   result=false;  
   e.printStackTrace();
  }
 
  PrintWriter out=null;
  JSONObject jo = new JSONObject();
  try {
   getResponse().setContentType("text/html;charset=utf-8");     
   jo.accumulate("success", result); 
   jo.accumulate("msg",msg);
   out = getResponse().getWriter();
   out.write(jo.toString());
   out.close();  
  } catch (IOException e) {
   log.debug("============whbmemo:后台输出结果错误!");
  }
}

 

原创粉丝点击