flex\java导入组件,通用版

 自己做的一个通用的导入组件

引用页面代码

  
  
  
  
  1. <importExcel:ImportExcel id="importExcel"  
  2.                                  width="700" 
  3.                                  height="400" 
  4.                                  fullModelName="platform.esb.ticket.model.PosTicketAssociation"  
  5.                                  daoName="posTicketAssociationDao" 
  6.                                  templateName="posTicketAssociation.xls" 
  7.                                  saveDatasSucess="{dataGrid.dataProvider=event.data as ArrayCollection; 
  8.                                                    dataProvider=event.data as ArrayCollection}"/> 

flex组件代码

 

  
  
  
  
  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <base:TitleWindow xmlns:mx="library://ns.adobe.com/flex/mx" 
  3.                xmlns:s="library://ns.adobe.com/flex/spark"  
  4.                xmlns:fx="http://ns.adobe.com/mxml/2009" 
  5.                xmlns:base="library://apps.czw.com/flex/base" 
  6.                width="100%" height="100%" 
  7.                facade="{FACADE}" mediator="{MEDIATOR}" moduleID="{NextID}" 
  8.                creationComplete="init()" 
  9.                title="导入的EXCEL数据列表" 
  10.                close="closeHandler(event)"
  11.     <fx:Declarations> 
  12.         <base:FileUpload id="uploadFile" 
  13.                          fileType="Excel" 
  14.                          complete="browsComplete()"/> 
  15.     </fx:Declarations> 
  16.     <fx:Metadata> 
  17.         [Event (name="saveDatasSucess", type="com.czw.apps.common.CzwEvent")] 
  18.     </fx:Metadata> 
  19.     <fx:Script> 
  20.         <![CDATA[ 
  21.             import com.czw.apps.common.CzwEvent; 
  22.             import com.czw.apps.model.importExcel.ImportExcelEnum; 
  23.             import com.czw.apps.model.importExcel.vo.ImportExcelVO; 
  24.             import com.czw.apps.ui.core.datagrid.controls.dataGridClasses.MDataGridColumn; 
  25.             import com.czw.apps.ui.core.datagrid.controls.dataGridClasses.filterEditors.WildcardFilterEditor; 
  26.              
  27.             import mx.collections.ArrayCollection; 
  28.             import mx.collections.ICollectionView; 
  29.             import mx.controls.Alert; 
  30.             import mx.controls.LinkButton; 
  31.             import mx.events.CloseEvent; 
  32.             import mx.managers.PopUpManager; 
  33.              
  34.             import spark.components.Button; 
  35.             import spark.components.HGroup; 
  36.              
  37.             private static const FACADE:Class=ImportExcelFacade; 
  38.             private static const MEDIATOR:Class=ImportExcelMediator; 
  39.             public static const NAME:String=getClassName(ImportExcel); 
  40.              
  41.             private static var serial:Number=0; 
  42.             [Bindable] 
  43.             public var excelDatas:ArrayCollection=new ArrayCollection(); 
  44.              
  45.             private var _fullVoName:String; 
  46.              
  47.             private var _fullModelName:String; 
  48.              
  49.             private var _daoName:String; 
  50.              
  51.             private var _templateName:String; 
  52.              
  53.             public function set fullModelName(_fullModelName:String):void 
  54.             { 
  55.                 this._fullModelName=_fullModelName; 
  56.             } 
  57.              
  58.             public function set fullVoName(_fullVoName:String):void 
  59.             { 
  60.                 this._fullVoName=_fullVoName; 
  61.             } 
  62.              
  63.             public function set daoName(_daoName:String):void 
  64.             { 
  65.                 this._daoName=_daoName; 
  66.             } 
  67.              
  68.             public function set templateName(_templateName:String):void 
  69.             { 
  70.                 this._templateName=_templateName; 
  71.             } 
  72.              
  73.             private static function get NextID():String 
  74.             { 
  75.                 return NAME + '+' + serial++; 
  76.             } 
  77.              
  78.             override protected function init():void 
  79.             { 
  80.                 createChildren(); 
  81.             } 
  82.              
  83.             public function addColumnName(headerText:Array,dataField:Array):void 
  84.             { 
  85.                 if(null==headerText||null==dataField||headerText.length!=dataField.length) 
  86.                 { 
  87.                     Alert.show("导入失败","温馨提示"); 
  88.                     return ; 
  89.                 }    
  90.                 var columns:Array=new Array(); 
  91.                 var col:MDataGridColumn=null
  92.                 for (var i:int=0;i<headerText.length;i++) 
  93.                 { 
  94.                     col=new MDataGridColumn(); 
  95.                     col.filterEditor=new ClassFactory(com.czw.apps.ui.core.datagrid.controls.dataGridClasses.filterEditors.WildcardFilterEditor); 
  96.                     col.dataField=dataField[i]; 
  97.                     col.headerText=headerText[i]; 
  98.                     columns.push(col); 
  99.                 } 
  100.                 ImpExcelGridData.columns=columns; 
  101.             } 
  102.              
  103.             protected function closeHandler(event:CloseEvent):void 
  104.             { 
  105.                 PopUpManager.removePopUp(this); 
  106.             } 
  107.              
  108.             override protected function createChildren():void
  109.               super.createChildren(); 
  110.               var importBtn:LinkButton=new LinkButton(); 
  111.               var downloadTemplatBtn:LinkButton=new LinkButton(); 
  112.               var hgroup:HGroup=new HGroup(); 
  113.               importBtn.addEventListener(MouseEvent.CLICK,importBtnClickHandler); 
  114.               importBtn.setStyle("fontWeight","bold"); 
  115.               importBtn.label="[导入模板]"
  116.               downloadTemplatBtn.setStyle("fontWeight","bold"); 
  117.               downloadTemplatBtn.label="[模板下载]"
  118.               downloadTemplatBtn.addEventListener(MouseEvent.CLICK,downloadTemplatBtnClickHandler); 
  119.               hgroup.top=-25; 
  120.               hgroup.right=40; 
  121.               hgroup.addElement(importBtn); 
  122.               hgroup.addElement(downloadTemplatBtn); 
  123.               contentGroup.addElement(hgroup); 
  124.             } 
  125.              
  126.              
  127.             private function importBtnClickHandler(event:Event):void 
  128.             { 
  129.                 uploadFile.browse(); 
  130.             } 
  131.              
  132.             private function browsComplete():void 
  133.             { 
  134.                 var excelData:ImportExcelVO=new ImportExcelVO; 
  135.                 excelData.content=uploadFile.data; 
  136.                 excelData.fullModelName=_fullModelName; 
  137.                 this.sendEvent(ImportExcelEnum.IMPORT_EXCEL_DATA,excelData); 
  138.             } 
  139.              
  140.             private function downloadTemplatBtnClickHandler(event:Event):void 
  141.             { 
  142.                 navigateToURL(new URLRequest('/api-management/templateDownload.do?fileName='+_templateName), '_blank'); 
  143.             } 
  144.              
  145.             protected function del_clickHandler(event:MouseEvent):void 
  146.             { 
  147.                 excelDatas.removeItemAt(excelDatas.getItemIndex(ImpExcelGridData.selectedItem)); 
  148.                 ImpExcelGridData.dataProvider=excelDatas; 
  149.             } 
  150.              
  151.             protected function saveDatas_clickHandler(event:MouseEvent):void 
  152.             { 
  153.                 var arr:Array=new Array(); 
  154.                 arr[0]=_daoName; 
  155.                 arr[1]=ImpExcelGridData.dataProvider; 
  156.                 this.sendEvent(ImportExcelEnum.SAVE_EXCEL_DATA,arr); 
  157.             } 
  158.              
  159.             public function saveDatasSucess(arr:ArrayCollection):void 
  160.             { 
  161.                 this.closeHandler(null); 
  162.                 this.dispatchEvent(new CzwEvent("saveDatasSucess",arr)); 
  163.             } 
  164.              
  165.         ]]> 
  166.     </fx:Script> 
  167.     <base:MDataGrid id="ImpExcelGridData" 
  168.                     dataProvider="{excelDatas}" 
  169.                     width="100%" 
  170.                     height="100%" 
  171.                     editable="true" 
  172.                     horizontalScrollPolicy="off" 
  173.                     verticalScrollPolicy="on" 
  174.                     > 
  175.     </base:MDataGrid> 
  176.      
  177.     <base:controlBarContent> 
  178.         <s:Button label="保存" click="saveDatas_clickHandler(event)" /> 
  179.         <s:Button label="删除" enabled="{ImpExcelGridData.selectedIndex!=-1}" click="del_clickHandler(event)" /> 
  180.         <base:SearchBox target="{ImpExcelGridData}"/> 
  181.         <s:Label text="{ICollectionView(ImpExcelGridData.dataProvider).length} / {ImpExcelGridData.originalCollection.length}" 
  182.                  verticalAlign="middle"/> 
  183.     </base:controlBarContent> 
  184. </base:TitleWindow> 

java:

 

  
  
  
  
  1. package com.zjht.sys.service.impl; 
  2.  
  3. import java.io.ByteArrayInputStream; 
  4. import java.lang.reflect.Method; 
  5. import java.math.BigDecimal; 
  6. import java.math.BigInteger; 
  7. import java.net.MalformedURLException; 
  8. import java.net.URISyntaxException; 
  9. import java.text.ParseException; 
  10. import java.text.SimpleDateFormat; 
  11. import java.util.ArrayList; 
  12. import java.util.HashMap; 
  13. import java.util.List; 
  14. import java.util.Map; 
  15.  
  16. import org.apache.poi.hssf.usermodel.HSSFCell; 
  17. import org.apache.poi.hssf.usermodel.HSSFRow; 
  18. import org.apache.poi.hssf.usermodel.HSSFSheet; 
  19. import org.apache.poi.hssf.usermodel.HSSFWorkbook; 
  20. import org.apache.poi.poifs.filesystem.POIFSFileSystem; 
  21. import org.springframework.beans.BeansException; 
  22. import org.springframework.context.ApplicationContext; 
  23. import org.springframework.context.ApplicationContextAware; 
  24. import org.springframework.stereotype.Service; 
  25.  
  26. import com.zjht.sys.model.ImportExcel; 
  27. import com.zjht.sys.service.ImportExcelService; 
  28.  
  29. import framework.generic.dao.GenericDao; 
  30. import framework.generic.dao.Model; 
  31.  
  32. @Service("importExcelService"
  33. public class ImportExcelServiceImpl implements ImportExcelService, ApplicationContextAware { 
  34.  
  35.     private ApplicationContext context; 
  36.  
  37.     @Override 
  38.     public void setApplicationContext(ApplicationContext context) throws BeansException { 
  39.         this.context = context; 
  40.     } 
  41.  
  42.     @SuppressWarnings("deprecation"
  43.     @Override 
  44.     public Map<String, ?> analyticExcel(ImportExcel importExcel) { 
  45.         List<Object> list = new ArrayList<Object>(); 
  46.         String dataField[] = null
  47.         String headerText[] = null
  48.         try { 
  49.             Class<?> ins = Class.forName(importExcel.getFullModelName()); 
  50.             POIFSFileSystem fs = new POIFSFileSystem(new ByteArrayInputStream(importExcel.getContent())); 
  51.             HSSFWorkbook workBook = new HSSFWorkbook(fs); 
  52.             HSSFSheet sheet = workBook.getSheetAt(0); 
  53.             int rows = sheet.getPhysicalNumberOfRows(); // 获得行数 
  54.             if (rows > 0) { 
  55.                 sheet.getMargin(HSSFSheet.TopMargin); 
  56.                 for (int j = 0; j < rows; j++) { // 行循环 
  57.                     HSSFRow row = sheet.getRow(j); 
  58.                     Object obj = ins.newInstance(); 
  59.                     if (row != null) { 
  60.                         int cells = row.getLastCellNum();// 获得列数 
  61.                         if (j == 0) { 
  62.                             dataField = new String[cells]; 
  63.                             headerText = new String[cells]; 
  64.                         } 
  65.                         for (short k = 0; k < cells; k++) { // 列循环 
  66.                             HSSFCell cell = row.getCell(k); 
  67.                             String value = ""
  68.                             if (cell != null) { 
  69.                                 switch (cell.getCellType()) { 
  70.                                 case HSSFCell.CELL_TYPE_NUMERIC: // 数值型 
  71.                                     value = String.valueOf((int) cell.getNumericCellValue()); 
  72.                                     break
  73.                                 /* 此行表示单元格的内容为string类型 */ 
  74.                                 case HSSFCell.CELL_TYPE_STRING: // 字符串型 
  75.                                     value = cell.getRichStringCellValue().toString(); 
  76.                                     break
  77.                                 case HSSFCell.CELL_TYPE_FORMULA:// 公式型 
  78.                                     // 读公式计算值 
  79.                                     value = String.valueOf(cell.getNumericCellValue()); 
  80.                                     if (value.equals("NaN")) {// 如果获取的数据值为非法值,则转换为获取字符串 
  81.                                         value = cell.getRichStringCellValue().toString(); 
  82.                                     } 
  83.                                     break
  84.                                 case HSSFCell.CELL_TYPE_BOOLEAN:// 布尔 
  85.                                     value = " " + cell.getBooleanCellValue(); 
  86.                                     break
  87.                                 case HSSFCell.CELL_TYPE_BLANK: // 空值 
  88.                                     value = ""
  89.                                     break
  90.                                 case HSSFCell.CELL_TYPE_ERROR: // 故障 
  91.                                     value = ""
  92.                                     break
  93.                                 default
  94.                                     value = cell.getRichStringCellValue().toString(); 
  95.                                 } 
  96.                             } 
  97.                             if (j == 0) { 
  98.                                 dataField[k] = value; 
  99.                             } else if (j == 1) { 
  100.                                 headerText[k] = value; 
  101.                             } else { 
  102.                                 String methodName = "set" + dataField[k].replaceFirst(dataField[k].substring(01), dataField[k].substring(01).toUpperCase()); 
  103.                                 Class<?> type = getParamType(ins, methodName); 
  104.                                 if (type == null || resolveValue(value, type) == null) { 
  105.                                     throw new RuntimeException("EXCEL解析失败(请确保您的EXCEL模板格式正确,如还有问题请联系研发部)"); 
  106.                                 } 
  107.                                 Method method = obj.getClass().getMethod(methodName, type); 
  108.                                 method.invoke(obj, resolveValue(value, type)); 
  109.                             } 
  110.                         } 
  111.                         if (j > 1) { 
  112.                             list.add(obj); 
  113.                         } 
  114.                     } 
  115.                 } 
  116.             } 
  117.         } catch (Exception e) { 
  118.             throw new RuntimeException("EXCEL解析失败(请确保您的EXCEL模板格式正确,如还有问题请联系研发部)" + e.getMessage()); 
  119.         } 
  120.         Map<String, Object> map = new HashMap<String, Object>(); 
  121.         map.put("headerText", headerText); 
  122.         map.put("dataField", dataField); 
  123.         map.put("list", list); 
  124.         return map; 
  125.     } 
  126.  
  127.     public static <T> T resolveValue(Object value, Class<T> valueClazz) { 
  128.         if (value == null
  129.             return null
  130.         Class<T> actualClazz = valueClazz; 
  131.         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS Z"); 
  132.         if (actualClazz == Boolean.class) { 
  133.             return actualClazz.cast(Boolean.valueOf(value.toString())); 
  134.         } else if (actualClazz == Character.class) { 
  135.             return actualClazz.cast(value.toString().charAt(0)); 
  136.         } else if (actualClazz == Integer.class) { 
  137.             return actualClazz.cast(new Integer(value.toString())); 
  138.         } else if (actualClazz == Double.class) { 
  139.             return actualClazz.cast(new Double(value.toString())); 
  140.         } else if (actualClazz == Float.class) { 
  141.             return actualClazz.cast(new Float(value.toString())); 
  142.         } else if (actualClazz == Short.class) { 
  143.             return actualClazz.cast(new Short(value.toString())); 
  144.         } else if (actualClazz == Byte.class) { 
  145.             return actualClazz.cast(new Byte(value.toString())); 
  146.         } else if (actualClazz == Long.class) { 
  147.             return actualClazz.cast(new Long(value.toString())); 
  148.         } else if (actualClazz == BigInteger.class) { 
  149.             return actualClazz.cast(new BigInteger(value.toString())); 
  150.         } else if (actualClazz == BigDecimal.class) { 
  151.             return actualClazz.cast(new BigDecimal(value.toString())); 
  152.         } else if (actualClazz == java.sql.Time.class) { 
  153.             return actualClazz.cast(java.sql.Time.valueOf(value.toString())); 
  154.         } else if (actualClazz == java.util.Date.class) { 
  155.             try { 
  156.                 return actualClazz.cast(sdf.parse(value.toString())); 
  157.             } catch (ParseException e) { 
  158.                 throw new RuntimeException("日期解析失败" + e.getMessage()); 
  159.             } 
  160.         } else if (actualClazz == java.sql.Date.class) { 
  161.             return actualClazz.cast(java.sql.Date.valueOf(value.toString())); 
  162.         } else if (actualClazz == java.sql.Timestamp.class) { 
  163.             return actualClazz.cast(java.sql.Timestamp.valueOf(value.toString())); 
  164.         } else if (actualClazz == java.net.URL.class) { 
  165.             try { 
  166.                 return actualClazz.cast(new java.net.URL(value.toString())); 
  167.             } catch (MalformedURLException e) { 
  168.                 e.printStackTrace(); 
  169.                 throw new RuntimeException("url解析失败" + e.getMessage()); 
  170.             } 
  171.         } else if (actualClazz == java.net.URI.class) { 
  172.             try { 
  173.                 return actualClazz.cast(new java.net.URI(value.toString())); 
  174.             } catch (URISyntaxException e) { 
  175.                 throw new RuntimeException("url解析失败" + e.getMessage()); 
  176.             } 
  177.         } 
  178.         if (actualClazz == value.getClass() || actualClazz.isAssignableFrom(value.getClass())) { 
  179.             return actualClazz.cast(value); 
  180.         } 
  181.         return null
  182.     } 
  183.  
  184.     private static Class<?> getParamType(Class<?> cl, String methodName) { 
  185.         try { 
  186.             Method[] methods = cl.getDeclaredMethods(); 
  187.             for (Method m : methods) { 
  188.                 String name = m.getName(); 
  189.                 if (methodName.equals(name)) { 
  190.                     Class<?>[] paramTypes = m.getParameterTypes(); 
  191.                     return paramTypes[0]; 
  192.                 } 
  193.             } 
  194.         } catch (Exception e) { 
  195.             e.printStackTrace(); 
  196.         } 
  197.         return null
  198.     } 
  199.  
  200.     @SuppressWarnings({ "unchecked""rawtypes" }) 
  201.     @Override 
  202.     public List<?> saveExcelDatas(String daoName, List<?> excelDatas) { 
  203.         GenericDao dao = (GenericDao) context.getBean(daoName); 
  204.         for (Object object : excelDatas) { 
  205.             dao.create((Model)object); 
  206.         } 
  207.         return dao.read(); 
  208.     } 
  209.  

 

你可能感兴趣的:(java,excel导入,通用版)