自己做的一个通用的导入组件
引用页面代码
- <importExcel:ImportExcel id="importExcel"
- width="700"
- height="400"
- fullModelName="platform.esb.ticket.model.PosTicketAssociation"
- daoName="posTicketAssociationDao"
- templateName="posTicketAssociation.xls"
- saveDatasSucess="{dataGrid.dataProvider=event.data as ArrayCollection;
- dataProvider=event.data as ArrayCollection}"/>
flex组件代码
- <?xml version="1.0" encoding="utf-8"?>
- <base:TitleWindow xmlns:mx="library://ns.adobe.com/flex/mx"
- xmlns:s="library://ns.adobe.com/flex/spark"
- xmlns:fx="http://ns.adobe.com/mxml/2009"
- xmlns:base="library://apps.czw.com/flex/base"
- width="100%" height="100%"
- facade="{FACADE}" mediator="{MEDIATOR}" moduleID="{NextID}"
- creationComplete="init()"
- title="导入的EXCEL数据列表"
- close="closeHandler(event)">
- <fx:Declarations>
- <base:FileUpload id="uploadFile"
- fileType="Excel"
- complete="browsComplete()"/>
- </fx:Declarations>
- <fx:Metadata>
- [Event (name="saveDatasSucess", type="com.czw.apps.common.CzwEvent")]
- </fx:Metadata>
- <fx:Script>
- <![CDATA[
- import com.czw.apps.common.CzwEvent;
- import com.czw.apps.model.importExcel.ImportExcelEnum;
- import com.czw.apps.model.importExcel.vo.ImportExcelVO;
- import com.czw.apps.ui.core.datagrid.controls.dataGridClasses.MDataGridColumn;
- import com.czw.apps.ui.core.datagrid.controls.dataGridClasses.filterEditors.WildcardFilterEditor;
- import mx.collections.ArrayCollection;
- import mx.collections.ICollectionView;
- import mx.controls.Alert;
- import mx.controls.LinkButton;
- import mx.events.CloseEvent;
- import mx.managers.PopUpManager;
- import spark.components.Button;
- import spark.components.HGroup;
- private static const FACADE:Class=ImportExcelFacade;
- private static const MEDIATOR:Class=ImportExcelMediator;
- public static const NAME:String=getClassName(ImportExcel);
- private static var serial:Number=0;
- [Bindable]
- public var excelDatas:ArrayCollection=new ArrayCollection();
- private var _fullVoName:String;
- private var _fullModelName:String;
- private var _daoName:String;
- private var _templateName:String;
- public function set fullModelName(_fullModelName:String):void
- {
- this._fullModelName=_fullModelName;
- }
- public function set fullVoName(_fullVoName:String):void
- {
- this._fullVoName=_fullVoName;
- }
- public function set daoName(_daoName:String):void
- {
- this._daoName=_daoName;
- }
- public function set templateName(_templateName:String):void
- {
- this._templateName=_templateName;
- }
- private static function get NextID():String
- {
- return NAME + '+' + serial++;
- }
- override protected function init():void
- {
- createChildren();
- }
- public function addColumnName(headerText:Array,dataField:Array):void
- {
- if(null==headerText||null==dataField||headerText.length!=dataField.length)
- {
- Alert.show("导入失败","温馨提示");
- return ;
- }
- var columns:Array=new Array();
- var col:MDataGridColumn=null;
- for (var i:int=0;i<headerText.length;i++)
- {
- col=new MDataGridColumn();
- col.filterEditor=new ClassFactory(com.czw.apps.ui.core.datagrid.controls.dataGridClasses.filterEditors.WildcardFilterEditor);
- col.dataField=dataField[i];
- col.headerText=headerText[i];
- columns.push(col);
- }
- ImpExcelGridData.columns=columns;
- }
- protected function closeHandler(event:CloseEvent):void
- {
- PopUpManager.removePopUp(this);
- }
- override protected function createChildren():void{
- super.createChildren();
- var importBtn:LinkButton=new LinkButton();
- var downloadTemplatBtn:LinkButton=new LinkButton();
- var hgroup:HGroup=new HGroup();
- importBtn.addEventListener(MouseEvent.CLICK,importBtnClickHandler);
- importBtn.setStyle("fontWeight","bold");
- importBtn.label="[导入模板]";
- downloadTemplatBtn.setStyle("fontWeight","bold");
- downloadTemplatBtn.label="[模板下载]";
- downloadTemplatBtn.addEventListener(MouseEvent.CLICK,downloadTemplatBtnClickHandler);
- hgroup.top=-25;
- hgroup.right=40;
- hgroup.addElement(importBtn);
- hgroup.addElement(downloadTemplatBtn);
- contentGroup.addElement(hgroup);
- }
- private function importBtnClickHandler(event:Event):void
- {
- uploadFile.browse();
- }
- private function browsComplete():void
- {
- var excelData:ImportExcelVO=new ImportExcelVO;
- excelData.content=uploadFile.data;
- excelData.fullModelName=_fullModelName;
- this.sendEvent(ImportExcelEnum.IMPORT_EXCEL_DATA,excelData);
- }
- private function downloadTemplatBtnClickHandler(event:Event):void
- {
- navigateToURL(new URLRequest('/api-management/templateDownload.do?fileName='+_templateName), '_blank');
- }
- protected function del_clickHandler(event:MouseEvent):void
- {
- excelDatas.removeItemAt(excelDatas.getItemIndex(ImpExcelGridData.selectedItem));
- ImpExcelGridData.dataProvider=excelDatas;
- }
- protected function saveDatas_clickHandler(event:MouseEvent):void
- {
- var arr:Array=new Array();
- arr[0]=_daoName;
- arr[1]=ImpExcelGridData.dataProvider;
- this.sendEvent(ImportExcelEnum.SAVE_EXCEL_DATA,arr);
- }
- public function saveDatasSucess(arr:ArrayCollection):void
- {
- this.closeHandler(null);
- this.dispatchEvent(new CzwEvent("saveDatasSucess",arr));
- }
- ]]>
- </fx:Script>
- <base:MDataGrid id="ImpExcelGridData"
- dataProvider="{excelDatas}"
- width="100%"
- height="100%"
- editable="true"
- horizontalScrollPolicy="off"
- verticalScrollPolicy="on"
- >
- </base:MDataGrid>
- <base:controlBarContent>
- <s:Button label="保存" click="saveDatas_clickHandler(event)" />
- <s:Button label="删除" enabled="{ImpExcelGridData.selectedIndex!=-1}" click="del_clickHandler(event)" />
- <base:SearchBox target="{ImpExcelGridData}"/>
- <s:Label text="{ICollectionView(ImpExcelGridData.dataProvider).length} / {ImpExcelGridData.originalCollection.length}"
- verticalAlign="middle"/>
- </base:controlBarContent>
- </base:TitleWindow>
java:
- package com.zjht.sys.service.impl;
- import java.io.ByteArrayInputStream;
- import java.lang.reflect.Method;
- import java.math.BigDecimal;
- import java.math.BigInteger;
- import java.net.MalformedURLException;
- import java.net.URISyntaxException;
- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import org.apache.poi.hssf.usermodel.HSSFCell;
- import org.apache.poi.hssf.usermodel.HSSFRow;
- import org.apache.poi.hssf.usermodel.HSSFSheet;
- import org.apache.poi.hssf.usermodel.HSSFWorkbook;
- import org.apache.poi.poifs.filesystem.POIFSFileSystem;
- import org.springframework.beans.BeansException;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.ApplicationContextAware;
- import org.springframework.stereotype.Service;
- import com.zjht.sys.model.ImportExcel;
- import com.zjht.sys.service.ImportExcelService;
- import framework.generic.dao.GenericDao;
- import framework.generic.dao.Model;
- @Service("importExcelService")
- public class ImportExcelServiceImpl implements ImportExcelService, ApplicationContextAware {
- private ApplicationContext context;
- @Override
- public void setApplicationContext(ApplicationContext context) throws BeansException {
- this.context = context;
- }
- @SuppressWarnings("deprecation")
- @Override
- public Map<String, ?> analyticExcel(ImportExcel importExcel) {
- List<Object> list = new ArrayList<Object>();
- String dataField[] = null;
- String headerText[] = null;
- try {
- Class<?> ins = Class.forName(importExcel.getFullModelName());
- POIFSFileSystem fs = new POIFSFileSystem(new ByteArrayInputStream(importExcel.getContent()));
- HSSFWorkbook workBook = new HSSFWorkbook(fs);
- HSSFSheet sheet = workBook.getSheetAt(0);
- int rows = sheet.getPhysicalNumberOfRows(); // 获得行数
- if (rows > 0) {
- sheet.getMargin(HSSFSheet.TopMargin);
- for (int j = 0; j < rows; j++) { // 行循环
- HSSFRow row = sheet.getRow(j);
- Object obj = ins.newInstance();
- if (row != null) {
- int cells = row.getLastCellNum();// 获得列数
- if (j == 0) {
- dataField = new String[cells];
- headerText = new String[cells];
- }
- for (short k = 0; k < cells; k++) { // 列循环
- HSSFCell cell = row.getCell(k);
- String value = "";
- if (cell != null) {
- switch (cell.getCellType()) {
- case HSSFCell.CELL_TYPE_NUMERIC: // 数值型
- value = String.valueOf((int) cell.getNumericCellValue());
- break;
- /* 此行表示单元格的内容为string类型 */
- case HSSFCell.CELL_TYPE_STRING: // 字符串型
- value = cell.getRichStringCellValue().toString();
- break;
- case HSSFCell.CELL_TYPE_FORMULA:// 公式型
- // 读公式计算值
- value = String.valueOf(cell.getNumericCellValue());
- if (value.equals("NaN")) {// 如果获取的数据值为非法值,则转换为获取字符串
- value = cell.getRichStringCellValue().toString();
- }
- break;
- case HSSFCell.CELL_TYPE_BOOLEAN:// 布尔
- value = " " + cell.getBooleanCellValue();
- break;
- case HSSFCell.CELL_TYPE_BLANK: // 空值
- value = "";
- break;
- case HSSFCell.CELL_TYPE_ERROR: // 故障
- value = "";
- break;
- default:
- value = cell.getRichStringCellValue().toString();
- }
- }
- if (j == 0) {
- dataField[k] = value;
- } else if (j == 1) {
- headerText[k] = value;
- } else {
- String methodName = "set" + dataField[k].replaceFirst(dataField[k].substring(0, 1), dataField[k].substring(0, 1).toUpperCase());
- Class<?> type = getParamType(ins, methodName);
- if (type == null || resolveValue(value, type) == null) {
- throw new RuntimeException("EXCEL解析失败(请确保您的EXCEL模板格式正确,如还有问题请联系研发部)");
- }
- Method method = obj.getClass().getMethod(methodName, type);
- method.invoke(obj, resolveValue(value, type));
- }
- }
- if (j > 1) {
- list.add(obj);
- }
- }
- }
- }
- } catch (Exception e) {
- throw new RuntimeException("EXCEL解析失败(请确保您的EXCEL模板格式正确,如还有问题请联系研发部)" + e.getMessage());
- }
- Map<String, Object> map = new HashMap<String, Object>();
- map.put("headerText", headerText);
- map.put("dataField", dataField);
- map.put("list", list);
- return map;
- }
- public static <T> T resolveValue(Object value, Class<T> valueClazz) {
- if (value == null)
- return null;
- Class<T> actualClazz = valueClazz;
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS Z");
- if (actualClazz == Boolean.class) {
- return actualClazz.cast(Boolean.valueOf(value.toString()));
- } else if (actualClazz == Character.class) {
- return actualClazz.cast(value.toString().charAt(0));
- } else if (actualClazz == Integer.class) {
- return actualClazz.cast(new Integer(value.toString()));
- } else if (actualClazz == Double.class) {
- return actualClazz.cast(new Double(value.toString()));
- } else if (actualClazz == Float.class) {
- return actualClazz.cast(new Float(value.toString()));
- } else if (actualClazz == Short.class) {
- return actualClazz.cast(new Short(value.toString()));
- } else if (actualClazz == Byte.class) {
- return actualClazz.cast(new Byte(value.toString()));
- } else if (actualClazz == Long.class) {
- return actualClazz.cast(new Long(value.toString()));
- } else if (actualClazz == BigInteger.class) {
- return actualClazz.cast(new BigInteger(value.toString()));
- } else if (actualClazz == BigDecimal.class) {
- return actualClazz.cast(new BigDecimal(value.toString()));
- } else if (actualClazz == java.sql.Time.class) {
- return actualClazz.cast(java.sql.Time.valueOf(value.toString()));
- } else if (actualClazz == java.util.Date.class) {
- try {
- return actualClazz.cast(sdf.parse(value.toString()));
- } catch (ParseException e) {
- throw new RuntimeException("日期解析失败" + e.getMessage());
- }
- } else if (actualClazz == java.sql.Date.class) {
- return actualClazz.cast(java.sql.Date.valueOf(value.toString()));
- } else if (actualClazz == java.sql.Timestamp.class) {
- return actualClazz.cast(java.sql.Timestamp.valueOf(value.toString()));
- } else if (actualClazz == java.net.URL.class) {
- try {
- return actualClazz.cast(new java.net.URL(value.toString()));
- } catch (MalformedURLException e) {
- e.printStackTrace();
- throw new RuntimeException("url解析失败" + e.getMessage());
- }
- } else if (actualClazz == java.net.URI.class) {
- try {
- return actualClazz.cast(new java.net.URI(value.toString()));
- } catch (URISyntaxException e) {
- throw new RuntimeException("url解析失败" + e.getMessage());
- }
- }
- if (actualClazz == value.getClass() || actualClazz.isAssignableFrom(value.getClass())) {
- return actualClazz.cast(value);
- }
- return null;
- }
- private static Class<?> getParamType(Class<?> cl, String methodName) {
- try {
- Method[] methods = cl.getDeclaredMethods();
- for (Method m : methods) {
- String name = m.getName();
- if (methodName.equals(name)) {
- Class<?>[] paramTypes = m.getParameterTypes();
- return paramTypes[0];
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
- @SuppressWarnings({ "unchecked", "rawtypes" })
- @Override
- public List<?> saveExcelDatas(String daoName, List<?> excelDatas) {
- GenericDao dao = (GenericDao) context.getBean(daoName);
- for (Object object : excelDatas) {
- dao.create((Model)object);
- }
- return dao.read();
- }
- }