1. 程式人生 > >java反射技術應用--靈活匯出excel

java反射技術應用--靈活匯出excel

業務需求如下:

根據開始和結束時間查詢,時間段內的工資明細,並匯出Excel表格(根據選中的欄位匯出該列資料)

Excel共3列資料 

|  年       |  月            | 具體工資明細項     如:績效,崗位補貼等 

|  year     | month      |   value



實體類如下

public class Salary implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String deptCode="";
	private String deptName=""
        private String pay="";
           .
           .
           .此處省略多個欄位

      public String getDeptCode() {
         return deptCode;
    }
    public void setDeptCode(String deptCode) {
        this.deptCode = deptCode;
    };
       public String getDeptName() {
        return deptName;
    }
    public void setDeptName(String deptName) {
        this.deptName = deptName;
    } 
       public String getPay() {
        return pay;
    }
    public void setPay(String pay) {
        this.pay = pay;
    }

}



@Controller
@RequestMapping("/salary")
public class SalaryController {

/**
     * 
     * @param session
     * @param startDate 起始時間
     * @param endDate 結束時間
     * @param model
     * @param type 匯出工資明細型別
     * @return
     */
    @RequestMapping(value = "/exportDataWithType", method = RequestMethod.GET)
    public ModelAndView exportDataWithType(HttpSession session,
    		@RequestParam(required=false) Date startDate,@RequestParam(required=false) Date endDate,
    		ModelMap model,@RequestParam(required=false)String type) {
    	
    	BaseUsers user = (BaseUsers)session.getAttribute(WebConstants.CURRENT_USER);
    	//設定查詢條件
        Criteria criteria = new Criteria();      
        if(StringUtils.isNotBlank(user.getUserCode())){
            criteria.put("staffCode", user.getUserCode());
        }
        if(startDate != null){
        	criteria.put("startDate", startDate);
        }
        if(endDate != null){
        	criteria.put("endDate", endDate);      
        }       
        //經過篩選後的資料
        List<Salary> newList = new ArrayList<Salary>();
    	try {
                //查詢所有資料
    		List<Salary> list = salaryService.queryListGerenForPage(criteria);
    		for(Salary li:list){
    			Salary salary = new Salary();
    			salary.setYear(li.getYear());
    			salary.setMonth(li.getMonth());
                        //根據選擇的明細  對第三列的值進行設定   setTing方法 
                       setThing(salary,type,getGetMethod(li,type));
        		newList.add(salary);
    		}
		} catch (Exception e) {
			e.printStackTrace();
		}
    	 ViewExcel2 viewExcel = new ViewExcel2();
         
         model.put("data", newList);
 		return new ModelAndView(viewExcel, model);
    }
    

    /**
     * 根據屬性名獲取get方法,並獲取對應值
     * @param obj  實體類
     * @param filed  屬性名
     * @return 返回該屬性對應的值
     */
    public  static Object getGetMethod(Object obj, String filed) {  
        Object o = null;
        try {  
            Class clazz = obj.getClass();  
            PropertyDescriptor pd = new PropertyDescriptor(filed, clazz);  
            Method getMethod = pd.getReadMethod();//獲得get方法  
            if (pd != null) {        
                o = getMethod.invoke(obj);//執行get方法返回一個Object                     
            }  
        }catch(Exception e) {
        	e.printStackTrace();
        }          
        return o;

    }  
    
    /**
     * 獲取對應set方法 並將值賦進去
     * @param obj 實體類
     * @param type 傳入工資明細型別 pay
     * @param s 需要設定的引數值  "1000.0"
     */
    public static void setThing(Object obj,String type,Object s){
    	Field field = null;
    	try {
			field = obj.getClass().getDeclaredField(type);
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		}
    	field.setAccessible(true);  
    	try {
			field.set((Object) obj, s);
		} catch (IllegalArgumentException e1) {
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			e1.printStackTrace();
		}
     }
    




        //內部類 生成Excel表格
       class ViewExcel2 extends AbstractExcelView {
		@Override
		protected void buildExcelDocument(Map<String, Object> model,
				HSSFWorkbook workbook, HttpServletRequest request,
				HttpServletResponse response) throws Exception {
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-disposition", "attachment;filename="+ new String("個人工資表.xls".getBytes(), "iso8859-1"));
			List<Salary> data = (List<Salary>) model.get("data");
			int rowNum = 1;
			HSSFRow row = null;
			HSSFSheet sheet = workbook.createSheet("新生列表");
			// 設定樣式
			HSSFFont cnFont = workbook.createFont();
			cnFont.setFontHeightInPoints((short) 10);
			cnFont.setFontName("宋體");
			HSSFCellStyle cnStyle = workbook.createCellStyle();
			cnStyle.setFont(cnFont);
			String password = null;
			// 設定首行資訊
			HSSFRow headerRow = sheet.createRow(0);			
			this.setExcelHeader(headerRow, data);		
			if (data != null) {
				for (Salary s : data) {
					row = sheet.createRow(rowNum++);
                                        //設定年份
                                       createNewCell(row, cnStyle, 0, s.getYear());
                                        //設定月份
                                       createNewCell(row, cnStyle, 1, s.getMonth());
					
					Field[] fields = s.getClass().getDeclaredFields();  				  
					String[]   name   =   new   String[fields.length]; 
                                      //獲取實體類 所有private 屬性
                                      Object[]   value   =   new  Object[fields.length]; 
                              try{
                                    Field.setAccessible(fields,   true);
                                    for   (int i = 0;i < name.length; i++)   { 
                                    //屬性名
                                     name[i]   =   fields[i].getName(); 
                                     //屬性值
                                      value[i]   =   fields[i].get(s); 
                                     if(fields[i].get(s)!=null && fields[i].get(s)!=""){
                                        //本業務邏輯
                            	         if(!(name[i].equals("year")) && !(name[i].equals("month")) &&! (name[i].equals("serialVersionUID")) ){
                                       //往  Excel 中第三列賦值    | year | month  |fields[i].get(s).toString()   共三列                                  
                                       createNewCell(row, cnStyle, 2,fields[i].get(s).toString());
                            	   }
                               }
                        } 
                    } 
                    catch(Exception   e){ 
                       e.printStackTrace(); 
                    } 
					
				}
			}
			// 設定首行資訊
			OutputStream ouputStream = response.getOutputStream();
			workbook.write(ouputStream);
			ouputStream.flush();
			ouputStream.close();
		}

		/**
		 * 按順序設定表頭
		 * 工資由多個不同項組成  根據需要匯出的型別不同 設定表頭資訊
		 * @return
		 */
		private void setExcelHeader(HSSFRow headerRow,List<Salary> data) {
			headerRow.createCell(0).setCellValue("年份");
			headerRow.createCell(1).setCellValue("月份");
			
			if(StringUtils.isNotBlank(data.get(0).getWages())){
				headerRow.createCell(2).setCellValue("應發額");
			}else if(StringUtils.isNotBlank(data.get(0).getPostWage())){
				headerRow.createCell(2).setCellValue("崗資");
			}else if(StringUtils.isNotBlank(data.get(0).getPay())){
				headerRow.createCell(2).setCellValue("薪資");
			}
                                .
                                .此處省略多個情況判斷
                                .



                        else if(StringUtils.isNotBlank(data.get(0).getMeritPay())){
				headerRow.createCell(2).setCellValue("績效");
			}else if(StringUtils.isNotBlank(data.get(0).getTask())){
				headerRow.createCell(2).setCellValue("崗位津貼");
			}
			
			
		}

		/**
		 * 生成單元格
		 * 
		 * @param row
		 * @param style
		 * @param columnIndex
		 * @param value
		 */
		private void createNewCell(HSSFRow row, HSSFCellStyle style,
				int columnIndex, String value) {
			if (row != null) {
				HSSFCell cell = row.createCell(columnIndex);
				cell.setCellStyle(style);
				if (value != null) {
					cell.setCellValue(value);
				}
			}
		}
		
		 

	}






}