Excelツールクラスのインポート

14022 ワード

前言
最近の高校のプラットフォームプロジェクトでは、多くのモジュールがExcelのインポートとエクスポートの機能を使用しているため、Excelのインポートとエクスポートを処理するためにExcelUtilクラスをカプセル化することにしました.
本プロジェクトの永続化層はJPA(下位層はhibernateで実現)を用いているので,インポートとエクスポートもいずれもエンティティクラスに基づいている.
ExcelUtilを作成する前に、ネットでいくつかの資料を調べました.JAvaでExcelを扱うサードパーティのオープンソースプロジェクトは主にPOIとJXLです.poiは機能が強いが、リソースが消費され、ビッグデータ量のインポート・エクスポートにはあまりよくない.jxlは機能は簡単ですが、性能は比較的良いです.
本プロジェクトのインポート・エクスポートでは、パフォーマンスの問題に注目し、jxlが提供する機能も基本的に十分であるため、jxlをサポートとして選択しました.
実戦
書き出しはリストをExcel(listToExcel)に変換することです
インポートとは、ExcelをList(excelToList)に変換することです.
インポート・エクスポートでは、データ・ソースが空で重複行があるなど、さまざまな問題が発生します.これらの問題を処理するためにExcelException例外クラスをカスタマイズしました.
ExcelExceptionクラス
package common.tool.excel;

public class ExcelException extends Exception {

	public ExcelException() {
		// TODO Auto-generated constructor stub
	}

	public ExcelException(String message) {
		super(message);
		// TODO Auto-generated constructor stub
	}

	public ExcelException(Throwable cause) {
		super(cause);
		// TODO Auto-generated constructor stub
	}

	public ExcelException(String message, Throwable cause) {
		super(message, cause);
		// TODO Auto-generated constructor stub
	}


}

次はこの文の主役です
ExcelUtil
登場したのは、一つのツールクラスとして、その中のすべての方法が静的で、使いやすい.
ExcelUitlクラス
/**
 * @author     : WH
 * @group      : tgb8
 * @Date       : 2014-1-2   9:13:21
 * @Comments   :     Excel   
 * @Version    : 1.0.0
 */

public class ExcelUtil  {
	
	/**
	 * @MethodName	: listToExcel
	 * @Description	:   Excel(           ,         ,         )
	 * @param list		   
	 * @param fieldMap		       Excel           
	 *              ,          EL      
	 *  :list      student,student   college  ,         ,      
	 * fieldMap.put("college.collegeName","    ")
	 * @param sheetName       
	 * @param sheetSize              
	 * @param out		   
	 * @throws ExcelException
	 */
	public static   void   listToExcel (
			List list ,
			LinkedHashMap fieldMap,
			String sheetName,
			int sheetSize,
			OutputStream out
			) throws ExcelException{
		
		
		if(list.size()==0 || list==null){
        	throw new ExcelException("          ");
        }
        
		if(sheetSize>65535 || sheetSize<1){
			sheetSize=65535;
		}
		
        //         OutputStream     
		WritableWorkbook wwb;
		try {
			wwb = Workbook.createWorkbook(out);
			
			//  2003 Excel          65536   ,      65535 
			//        ,          ,          
			//1.           
			double sheetNum=Math.ceil(list.size()/new Integer(sheetSize).doubleValue());
			
			//2.        ,        
			for(int i=0; ilist.size()-1 ? list.size()-1 : (i+1)*sheetSize-1;
					//     
					fillSheet(sheet, list, fieldMap, firstIndex, lastIndex);
				}
			}
			
			wwb.write();
			wwb.close();
		
		}catch (Exception e) {
			e.printStackTrace();
			//   ExcelException,     
			if(e instanceof ExcelException){
				throw (ExcelException)e;
			
			//          ExcelException   
			}else{
				throw new ExcelException("  Excel  ");
			}
		}
			
	}
	
	/**
	 * @MethodName	: listToExcel
	 * @Description	:   Excel(           ,         ,      2003      )
	 * @param list		   
	 * @param fieldMap		       Excel           
	 * @param out		   
	 * @throws ExcelException
	 */
	public static    void   listToExcel (
			List list ,
			LinkedHashMap fieldMap,
			String sheetName,
			OutputStream out
			) throws ExcelException{
		
		listToExcel(list, fieldMap, sheetName, 65535, out);
		
	}
	
	
	/**
	 * @MethodName	: listToExcel
	 * @Description	:   Excel(      ,           )
	 * @param list		   
	 * @param fieldMap		       Excel           
	 * @param sheetSize                 
	 * @param response	  response        
	 * @throws ExcelException
	 */
	public static    void   listToExcel (
			List list ,
			LinkedHashMap fieldMap,
			String sheetName,
			int sheetSize,
			HttpServletResponse response 
			) throws ExcelException{
		
		//            :      
		String fileName=new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()).toString();
		
		//  response   
		response.reset();          
        response.setContentType("application/vnd.ms-excel");        //    excel  
        response.setHeader("Content-disposition","attachment; filename="+fileName+".xls" );

        //            
        try {
        	
        	OutputStream out=response.getOutputStream();
        	listToExcel(list, fieldMap, sheetName, sheetSize,out );
			
		} catch (Exception e) {
			e.printStackTrace();
			
			//   ExcelException,     
			if(e instanceof ExcelException){
				throw (ExcelException)e;
			
			//          ExcelException   
			}else{
				throw new ExcelException("  Excel  ");
			}
		}
	}
	
	
	/**
	 * @MethodName	: listToExcel
	 * @Description	:   Excel(      ,       2003      )
	 * @param list		   
	 * @param fieldMap		       Excel           
	 * @param response	  response        
	 * @throws ExcelException
	 */
	public static   void   listToExcel (
			List list ,
			LinkedHashMap fieldMap,
			String sheetName,
			HttpServletResponse response 
			) throws ExcelException{
		
		listToExcel(list, fieldMap, sheetName, 65535, response);
	}
	
	/**
	 * @MethodName			: excelToList
	 * @Description				:  Excel   List
	 * @param in					:   Excel    
	 * @param sheetIndex		:         
	 * @param entityClass		:List      (Excel                )
	 * @param fieldMap			:Excel                  Map
	 * @param uniqueFields	:        (     ),          
	 * @return						:List
	 * @throws ExcelException
	 */
	public static   List  excelToList(
			InputStream in,
			String sheetName,
			Class entityClass,
			LinkedHashMap fieldMap,
			String[] uniqueFields
			) throws ExcelException{
		
		//      list
		List resultList=new ArrayList();
		
		try {
			
			//  Excel     WorkBook
			Workbook wb=Workbook.getWorkbook(in);
			//     
			Sheet sheet=wb.getSheet(sheetName);
			
			//          
			int realRows=0;
			for(int i=0;i excelFieldList=Arrays.asList(excelFieldNames);
			for(String cnName : fieldMap.keySet()){
				if(!excelFieldList.contains(cnName)){
					isExist=false;
					break;
				}
			}
			
			//        ,     ,    
			if(!isExist){
				throw new ExcelException("Excel        ,       ");
			}
			
			
			//        Map ,             
			LinkedHashMap colMap=new LinkedHashMap();
			for(int i=0;i entry : fieldMap.entrySet()){
					//       
					String cnNormalName=entry.getKey();
					//       
					String enNormalName=entry.getValue();
					//           
					int col=colMap.get(cnNormalName);
					
					//           
					String content=sheet.getCell(col, i).getContents().toString().trim();
					
					//     
					setFieldValueByName(enNormalName, content, entity);
				}
				
				resultList.add(entity);
			}
		} catch(Exception e){
			e.printStackTrace();
			//   ExcelException,     
			if(e instanceof ExcelException){
				throw (ExcelException)e;
			
			//          ExcelException   
			}else{
				e.printStackTrace();
				throw new ExcelException("  Excel  ");
			}
		}
		return resultList;
	}
	
	
	
	
	
	/**/
	/**
	 * @MethodName	: getFieldValueByName
	 * @Description	:           
	 * @param fieldName	   
	 * @param o	  
	 * @return	   
	 */
	private static  Object getFieldValueByName(String fieldName, Object o) throws Exception{
		
		Object value=null;
		Field field=getFieldByName(fieldName, o.getClass());
		
		if(field !=null){
			field.setAccessible(true);
			value=field.get(o);
		}else{
			throw new ExcelException(o.getClass().getSimpleName() + "        "+fieldName);
		}
		
		return value;
	}
	
	/**
	 * @MethodName	: getFieldByName
	 * @Description	:          
	 * @param fieldName    
	 * @param clazz	       
	 * @return   
	 */
	private static Field getFieldByName(String fieldName, Class>  clazz){
		//         
		Field[] selfFields=clazz.getDeclaredFields();
		
		//          ,   
		for(Field field : selfFields){
			if(field.getName().equals(fieldName)){
				return field;
			}
		}
		
		//  ,            ,      
		Class> superClazz=clazz.getSuperclass();
		if(superClazz!=null  &&  superClazz !=Object.class){
			return getFieldByName(fieldName, superClazz);
		}
		
		//          ,    
		return null;
	}
	
	
	
	/**
	 * @MethodName	: getFieldValueByNameSequence
	 * @Description	: 
	 *                    
	 *         , userName ,          , student.department.name 
	 * 
	 * @param fieldNameSequence               
	 * @param o   
	 * @return     
	 * @throws Exception
	 */
	private static  Object getFieldValueByNameSequence(String fieldNameSequence, Object o) throws Exception{
		
		Object value=null;
		
		// fieldNameSequence    
		String[] attributes=fieldNameSequence.split("\\.");
		if(attributes.length==1){
			value=getFieldValueByName(fieldNameSequence, o);
		}else{
			//           
			Object fieldObj=getFieldValueByName(attributes[0], o);
			String subFieldNameSequence=fieldNameSequence.substring(fieldNameSequence.indexOf(".")+1);
			value=getFieldValueByNameSequence(subFieldNameSequence, fieldObj);
		}
		return value; 
	    
	} 
	
	
	/**
	 * @MethodName	: setFieldValueByName
	 * @Description	:              
	 * @param fieldName     
	 * @param fieldValue	   
	 * @param o	  
	 */
	private static void setFieldValueByName(String fieldName,Object fieldValue,Object o) throws Exception{
		
			Field field=getFieldByName(fieldName, o.getClass());
			if(field!=null){
				field.setAccessible(true);
				//      
				Class> fieldType = field.getType();  
	            
				//           
				if (String.class == fieldType) {  
	                field.set(o, String.valueOf(fieldValue));  
	            } else if ((Integer.TYPE == fieldType)  
	                    || (Integer.class == fieldType)) {  
	                field.set(o, Integer.parseInt(fieldValue.toString()));  
	            } else if ((Long.TYPE == fieldType)  
	                    || (Long.class == fieldType)) {  
	                field.set(o, Long.valueOf(fieldValue.toString()));  
	            } else if ((Float.TYPE == fieldType)  
	                    || (Float.class == fieldType)) {  
	                field.set(o, Float.valueOf(fieldValue.toString()));  
	            } else if ((Short.TYPE == fieldType)  
	                    || (Short.class == fieldType)) {  
	                field.set(o, Short.valueOf(fieldValue.toString()));  
	            } else if ((Double.TYPE == fieldType)  
	                    || (Double.class == fieldType)) {  
	                field.set(o, Double.valueOf(fieldValue.toString()));  
	            } else if (Character.TYPE == fieldType) {  
	                if ((fieldValue!= null) && (fieldValue.toString().length() > 0)) {  
	                    field.set(o, Character  
	                            .valueOf(fieldValue.toString().charAt(0)));  
	                }  
	            }else if(Date.class==fieldType){
	            	field.set(o, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(fieldValue.toString()));
	            }else{
	            	field.set(o, fieldValue);
	            }
			}else{
				throw new ExcelException(o.getClass().getSimpleName() + "        "+fieldName);
			}
	}
	
	
	/**
	 * @MethodName	: setColumnAutoSize
	 * @Description	:               
	 * @param ws
	 */
	private static void setColumnAutoSize(WritableSheet ws,int extraWith){
		//             
		for(int i=0;i void fillSheet(
			WritableSheet sheet,
			List list,
			LinkedHashMap fieldMap,
			int firstIndex,
			int lastIndex
			)throws Exception{
		
		//                  
		String[] enFields=new String[fieldMap.size()];
		String[] cnFields=new String[fieldMap.size()];
		
		//    
		int count=0;
		for(Entry entry:fieldMap.entrySet()){
			enFields[count]=entry.getKey();
			cnFields[count]=entry.getValue();
			count++;
		}
		//    
		for(int i=0;i

このツールクラスには4つのリロードされたエクスポート方法と1つのインポート方法があり、実際の状況に応じて選択できます.
まとめ
インポートメソッドとエクスポートメソッドは、fieldMapパラメータ(クラスの英語プロパティとExcelの中国語カラムヘッダの対応関係)を渡すことで、エンティティクラスとExcelを接続します.
エクスポート時にローカルファイルシステムにエクスポートするかブラウザにエクスポートするか、ワークシートごとにサイズをカスタマイズできます.
インポート時にビジネス・プライマリ・キーの組合せuniqueFieldsをカスタマイズすることで、Excelに重複行があるかどうかを検出できます.