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;
    }

}



扫描二维码关注公众号,回复: 4295468 查看本文章
@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);
				}
			}
		}
		
		 

	}






}




猜你喜欢

转载自blog.csdn.net/wuxians/article/details/65631348