POI操做Excel導入導出

package com.gzbugu.util;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;


import com.gzbugu.action.ActionBase;
import com.gzbugu.common.commonService.ICommonService;


/**
 * @author ylh
 */
public class ExcelAction extends ActionBase{

private Map downExcelAttrsMap;
private String fileName;
public ICommonService commonService;

/**************************	 導入Excel	*****************************************/ 

/**
* 初始化時候加載applicationContext.xml獲取commonService
* @throws Exception
*/
public ExcelAction() throws Exception{
try {
BeanFactory beanFactory = new ClassPathXmlApplicationContext("applicationContext.xml");
commonService = (ICommonService)beanFactory.getBean("commonService");
if(null==commonService){
throw new Exception("初始化commonServeice失敗,請檢查applicationContext.xml文件路徑是否位於編譯後的classes文件src目錄下");
}
} catch (Exception e) {
throw new Exception("初始化commonServeice失敗,請檢查applicationContext.xml文件路徑是否位於編譯後的classes文件src目錄下");
}
}

/**
* 導入Excel入口方法
* 
* @param excelUrl 已存在的Excel文件路徑
* @param beanPropertyNames	【對象.屬性】 對應着表頭                        例:String[] beanPropertyNames = {"BusiCpar.depNames","BusiCpar.repUserNames"}
* @param beansRelative	            每行若是存在多個對象,則表示對象間的關係, 對象間的id必須符合插入的前後順序,默認的對象保存進數據庫的順序是從左往右,AAA.id=BusiBaseinfo.AAAId, BusiBaseinfo.id=BusiObservePlan.busiBaseInfoId    例:String[]	beansRelative = {"BusiBaseinfo.id=BusiCpar.baseinfoId","BusiCpar.id=BusiCparMeasure.cparId"}
* @return 返回一個list對象,其元素是每行包含的對象數組,對象順序是beanPropertyNames定義時對象的順序
* @throws Exception
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public List importExcel(String excelUrl, String[] beanPropertyNames, String[] beansRelative) throws Exception{
if(null==excelUrl||"".equals(excelUrl)){
throw new Exception("Excel文件路徑不容許爲空");
}
if(null==beanPropertyNames||0==beanPropertyNames.length){
     	throw new Exception("對象.屬性名不容許爲空");
   }

//讀取Excel文件
File file = new File(excelUrl); 
FileInputStream is = new FileInputStream(file);
//建立 POI文件系統對象
Workbook wb = WorkbookFactory.create(is);
        Sheet sheet = wb.getSheetAt(0);
        Row row;
        Cell cell;
        List list = new LinkedList();
        
        String beanPackagePrefix = "com.gzbugu.domain";	//映射對象的目錄,針對不一樣的項目可能須要改變
        
        //從第三行開始,第一行是標題,第二行是表頭,第三行開始時文件內容
        for ( int j =2, lent=sheet.getLastRowNum()+1; j < lent; j++) {  
            row = sheet.getRow(j); 
            //根據對象名生成相應類型的對象
            Map map = this.createBeans(beanPackagePrefix, beanPropertyNames);
            //按照每行內容將之設置到對象中
            if (null != row) {  
            	int colNum = beanPropertyNames.length;
                for (int k = 0; k < colNum; k++) {  
                    cell = row.getCell(k); 
                    Object valueObject=this.getCellValue(cell);
                    //把對應的Excel單元格中的內容賦值到對象中,map中保存的是對象的引用,因此直接修改對象的值就行,不用返回值
                    setValueToBean(map,beanPropertyNames[k],valueObject);
                }  
            }
            //得到全部對象名字
            String[] beanNames = this.getBeanNames(beanPropertyNames);
            int len = beanNames.length;
            //生成對象間ID的關聯關係
            if(len>1&&beansRelative.length!=0){
            	map = this.relativeObjects(map, beansRelative, beanNames);
            }            
            //統一保存全部對象到數組中
            Object[] objs = new Object[len];
            for(int i=0; i<len; i++){
            	objs[i]=map.get(beanNames[i].trim());
            }
            //將每行數據的對象數組保存到list中返回
            list.add(objs);
        }  
return list;
}

/**
* 對象間關聯值設置
* 對象間的id必須符合插入的前後順序,默認的對象保存進數據庫的順序是從左往右
* AAA.id=BusiBaseinfo.AAAId, BusiBaseinfo.id=BusiObservePlan.busiBaseInfoId
* @param map Excel表格一行所包含的對象
* @param beansRelative	對象之間的ID的關聯關係
* @param beanNames	所包含對象的名稱
* @return
*/
@SuppressWarnings("rawtypes")
public Map relativeObjects(Map map, String[] beansRelative, String[] beanNames){
int len = beansRelative.length;
for(int i=0; i<len; i++){
String relative = beansRelative[i];
String[] beanNameDotProperty = relative.split("=");
String leftBeanNameDotProperty = beanNameDotProperty[0].trim();
String rightBeanNameDotProperty = beanNameDotProperty[1].trim();

//處理句點左邊
String[] leftBeanNameAndProperty = leftBeanNameDotProperty.split("\\.");
String leftBeanName = leftBeanNameAndProperty[0];
String leftProperty = leftBeanNameAndProperty[1];
Object idValue = null;
//若是左邊的是對象.屬性中的屬性是id,則保存左邊的對象
if("id".equals(leftProperty)){
this.getCommonService().saveDemo(map.get(leftBeanName));
}
//保存以後獲取左邊對象的id
Method getterMethod = null;
try {
getterMethod = map.get(leftBeanName).getClass().getMethod(this.getterMethodName(leftProperty));
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
try {
idValue = getterMethod.invoke(map.get(leftBeanName));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}

//處理等號右邊
String[] rightBeanNameAndProperty = rightBeanNameDotProperty.split("\\.");
String rightBeanName = rightBeanNameAndProperty[0];
String rightProperty = rightBeanNameAndProperty[1];
Method setterMethod = null;
try {
//獲取setter方法的類型
Method getMethod = map.get(rightBeanName).getClass().getMethod(this.getterMethodName(rightProperty));
//設置setter值
setterMethod = map.get(rightBeanName).getClass().getMethod(this.setterMethodName(rightProperty),getMethod.getReturnType());
try {
setterMethod.invoke(map.get(rightBeanName),idValue);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
return map;
}

/**
* 把單元格里面的值賦值到相應的對象中
* @param map 每行所包含的對象map
* @param beanPropertyName  表頭
* @param value	Excel單元格中的值
*/
@SuppressWarnings("rawtypes")
public void setValueToBean(Map map, String beanPropertyName,Object value){
String[] beanNameAndPropertyName = beanPropertyName.split("\\."); //拆分表頭的     對象.屬性
String beanName = beanNameAndPropertyName[0];	 //對象名稱
String propertyName = beanNameAndPropertyName[1];	//屬性名稱
Object currentObject = map.get(beanName);
Method met = null;
try {
try {
//根據其getter方法來獲取參數類型
met = currentObject.getClass().getMethod(this.getterMethodName(propertyName));
Class type = met.getReturnType();
String typeName = type.getSimpleName().toLowerCase();
//針對不一樣參數轉換值
if (null!=value) {
String str=(value.toString()).trim();
if (!"".equals(str)&&str.length()>0) {
if("date".equals(typeName)){
value =(Date)value;
}else if("integer".equals(typeName)){
value = ((Double)value).intValue();
}
//經過setter方法設置到對象中
met = currentObject.getClass().getMethod(this.setterMethodName(propertyName),type);
value = met.invoke(currentObject,value); 
}
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (SecurityException e1) {
e1.printStackTrace();
}
}

/**
* 根據對象名字及實例化對象,默認最多隻能一行Excel數據有5個對象
* @param beanPropertyNames
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public Map createBeans(String beanPackagePrefix, String[] beanPropertyNames){
Object objectOne = null,objectTwo = null,objectThree = null,objectFour = null,objectFive = null;
Map map = new HashMap();
String[] beanNames = this.getBeanNames(beanPropertyNames);
        int len = beanNames.length;
        //根據對象的個數默認生成相應個數的對象,最多隻能5個
        for(int i=0; i<len; i++){
        	if(0==i){
        	 objectOne = this.newInstanceBean(beanPackagePrefix, beanNames[0].trim());
        	 map.put(beanNames[0].trim(), objectOne);
        	}else if(1==i){
        	 objectTwo = this.newInstanceBean(beanPackagePrefix, beanNames[1].trim());
        	 map.put(beanNames[1].trim(), objectTwo);
        	}else if(2==i){
        	 objectThree = this.newInstanceBean(beanPackagePrefix, beanNames[2].trim());
        	 map.put(beanNames[2].trim(), objectThree);
        	}else if(3==i){
        	 objectFour = this.newInstanceBean(beanPackagePrefix, beanNames[3].trim());
        	 map.put(beanNames[3].trim(), objectFour);
        	}else if(4==i){
        	 objectFive = this.newInstanceBean(beanPackagePrefix, beanNames[4].trim());
        	 map.put(beanNames[4].trim(), objectFive);
        	}
        }
        return map;
}

/**
* 根據  【對象.屬性】數組 獲取全部對象名
* @param beanPropertyNames
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public String[] getBeanNames(String[] beanPropertyNames){
Set set = new LinkedHashSet();
int len = beanPropertyNames.length;
for(int i=0; i<len; i++){
String[] beanNameAndProperty = beanPropertyNames[i].split("\\.");
String beanName = beanNameAndProperty[0];
set.add(beanName);
}
String str = set.toString();
return str.substring(1, str.length()-1).split(",");
}

/**
* 根據對象名實例化對象
* @param beanName
* @return
*/
@SuppressWarnings("rawtypes")
public Object newInstanceBean(String beanPackagePrefix, String beanName){
String bean = beanPackagePrefix + "." + beanName.trim();
Class clazz = null;
Object object = null;
try {
clazz = Class.forName(bean);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
object = clazz.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return object;
}

/**
* 得到Excel單元格內容
* @param cell
* @return
*/
public Object getCellValue(Cell cell){
Object object = null;
if (null != cell) {  
            switch (cell.getCellType()) {  
           case Cell.CELL_TYPE_NUMERIC: // 數字 
   if (DateUtil.isCellDateFormatted(cell)) {//日期
       double d = cell.getNumericCellValue();
       object = DateUtil.getJavaDate(d);  
   }else {
   	object = cell.getNumericCellValue();  
} 
               break;  
           case Cell.CELL_TYPE_STRING: // 字符串  
           	object = cell.getStringCellValue();  
               break;  
           case Cell.CELL_TYPE_BOOLEAN: // Boolean  
           	object = cell.getBooleanCellValue();  
               break;  
           case Cell.CELL_TYPE_FORMULA: // 公式  
           	object = cell.getCellFormula();  
               break;  
           case Cell.CELL_TYPE_BLANK: // 空值  
           	object = "";
               break;  
           case Cell.CELL_TYPE_ERROR: // 故障  
           	object = "";  
               break;  
           default:  
           	object = "未知類型";  
               break;  
       }  
        } else {  
            return null;
        }  
return object;
}


/**************************	 生成Excel	*****************************************/ 



/**
*
      使用方法方法:copy下面的配置到本身的strut.xml裏面,修改XXX,對應的方法返回SUCCESS
      
      此段爲自定義:
  <action name="XXX" class="XXX" method="XXX">
  	  <result type="chain">
  	  <param name="actionName">getDownloadExcel</param> 
  	  <param name="downExcelAttrsMap">${downExcelAttrsMap}</param>	 //downExcelAttrsMap爲map,須要在action中有setter跟getter方法
  	  </result>
  	   </action>
  	   
  	       此段爲公共,一個項目只須要有一個就行:    
  <action name="getDownloadExcel" class="com.gzbugu.util.ExcelAction">
  <result name="success" type="stream">
<param name="contentType">application/octet-stream;charset=ISO-8859-1</param>
<param name="contentDisposition">attachment;filename="${fileName}"</param>
<param name="InputName">downloadExcel</param>
</result>
  </action>


* downExcelAttrsMap包括參數的key以下:
* @param valueList	  	   必須,類型list,經過hql查詢數據庫後返回的對象List,支持關聯查詢後返回的list 
* @param beanPropertyNames	   必須,類型string[],須要被輸出的值屬性,通常狀況下是使用[對象.屬性]
  1.若是存在某些列是狀態值須要被替換的:{"BusiObservePlan.name","propertyName,0:我的計劃,1:部門月度計劃,2:安監部計劃", "xxxx","BusiObservePlan.planType,0:我的計劃,1:部門月度計劃,2:安部計劃"}
  2.若是涉及到常量或統計的列,使用常量字符定義'constant'等,但字符中不容許包含".",其對應值爲constantMap中的list(順序須要本身匹配),而constantMap中的key爲'constant',即 :constantMap.put('constant',list)
* @param fileName	     必須,類型string,生成excel的名稱
* 
* @param titleNames   二選一,必須,Excel表頭(與excelUrl對應,若是excelUrl存在,則執行excelUrl)
* @param excelUrl	     二選一,必須,Excel模板(與titleNames對應,若是excelUrl存在,則執行excelUrl)
* 
* @param constantMap	              可選,存放beanPropertyNames定義的常量值list,鍵爲對應的beanPropertyNames的值
* @param sheetName  	   可選,Excel的sheet的名字
* @param targetRowContent	   可選,注意:若是存在多個元素firstRowNum必須是不一樣的,內容放在指定的行rowNum指定的行數,從0開始,startCol指定的開始列數,endCol指定的結束列數,用於合併單元格存放內容,content填入的內容,{"firstRowNum|lastRowNum|startCol|endCol|content"};
* @param lastRowContent	   可選,內容放在Excel的最後一行,startCol指定的開始列數,endCol指定的結束列數,用於合併單元格存放內容,content填入的內容,{"startCol|endCol|content"};
* 
*/
@SuppressWarnings("rawtypes")
public InputStream getDownloadExcel(){
List valuelist = (List)downExcelAttrsMap.get("valueList");	 //list數據
String[] beanPropertyNames = (String[]) downExcelAttrsMap.get("beanPropertyNames");	 //表頭對應的屬性名稱
fileName = ((String) downExcelAttrsMap.get("fileName"));	//生成Excel的文件名稱
if(null==fileName||"".equals(fileName)){
try {
throw new Exception("fileName是必填項,不容許爲空");
} catch (Exception e) {
e.printStackTrace();
}
}else if(fileName.endsWith(".xls")||fileName.endsWith(".xlsx")){
fileName = fileName.replace(".xls", "").replace(".xlsx", "")+".xls";
}
String[] titleNames = (String[]) downExcelAttrsMap.get("titleNames");	 //表頭
String excelUrl = (String) downExcelAttrsMap.get("excelUrl");	 //Excel模板路徑
String sheetName = (String) downExcelAttrsMap.get("sheetName");	 //sheet名稱
String[] targetRowContent = (String[]) downExcelAttrsMap.get("targetRowContent");	 //內容放在指定的行
String[] lastRowContent = (String[]) downExcelAttrsMap.get("lastRowContent");	 //內容放在Excel的最後一行
Map constantMap =  (Map) downExcelAttrsMap.get("constantMap");	 //存放常量值list


InputStream is = null;
try {
is = this.createExcelFile(valuelist, sheetName, beanPropertyNames, titleNames, excelUrl, targetRowContent, lastRowContent, constantMap);
} catch (Exception e1) {
e1.printStackTrace();
}
try {
fileName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if(null==is) System.out.print("Excel生成失敗,文件不存在,你是否是寫錯了啊...");
return is;
}

public InputStream createExcelFile(List valueList, String sheetName, String[] beanPropertyNames, String[] titleNames, String excelUrl, String[] targetRowContent, String[] lastRowContent, Map map) throws Exception{ 
Workbook wb;
Sheet sheet;
Cell cell;
Row row;
if(null==excelUrl){
wb = new HSSFWorkbook();
       sheet = wb.createSheet(sheetName.replace(".xls", ""));
       //單元格默認寬度爲20
       sheet.setDefaultColumnWidth(20);
      
       sheet.addMergedRegion(new CellRangeAddress(0,0,0,beanPropertyNames.length-1));
       Row titleRow = sheet.createRow(0);
       titleRow.setHeightInPoints(20f);
       Cell titleCell = titleRow.createCell(0);
       titleCell.setCellValue(sheetName.replace(".xls", ""));
       titleCell.setCellStyle(this.getTitleCellStyle(wb));
       
       //表頭
       Row headerRow = sheet.createRow(1);
       headerRow.setHeightInPoints(18f);
       if(null==titleNames){
       	throw new Exception("表頭不容許爲空");
       }
       for (int i = 0; i < titleNames.length; i++) {
           cell = headerRow.createCell(i);
           cell.setCellValue(titleNames[i]);
           cell.setCellStyle(this.getHeaderCellStyle(wb));
       }
       //freeze the first row
       sheet.createFreezePane(0, 1);
}else{
//讀取Excel文件
 	 File file = new File(excelUrl); 
 	 FileInputStream is = new FileInputStream(file);
 	 //建立 POI文件系統對象
 	 wb = WorkbookFactory.create(is);
 	 sheet = wb.getSheetAt(0);
  
 	 Row titleRow = sheet.getRow(0);
       titleRow.setHeightInPoints(25f);
       Cell titleCell = titleRow.createCell(0);
       titleCell.setCellValue(sheetName.replace(".xls", ""));
       titleCell.setCellStyle(this.getTitleCellStyle(wb));
}

if(null!=targetRowContent){
//填入targetRowContent指定的內容
int targetRowContentLength = targetRowContent.length;
for(int l=0; l<targetRowContentLength; l++){
String target = targetRowContent[l];
String[] contents = target.split("\\|");
int firstRowNum = Integer.parseInt(contents[0]);
int lastRowNum = Integer.parseInt(contents[1]);
int startCol = Integer.parseInt(contents[2]);
int endCol = Integer.parseInt(contents[3]);
String content = contents[4];
row = sheet.createRow(firstRowNum);
cell = row.createCell(startCol);
cell.setCellValue(content);
sheet.addMergedRegion(new CellRangeAddress(firstRowNum,lastRowNum,startCol,endCol-1));
}
}


//填入list內容
        int rownum = sheet.getLastRowNum()+1;
        int listSize = null==valueList?0:valueList.size();
        int beanPropertyNamesLength = null==beanPropertyNames?0:beanPropertyNames.length;
        for (int i = 0; i < listSize; i++, rownum++) {
            row = sheet.createRow(rownum);
            Object currentObj = valueList.get(i);
            for ( int j=0; j < beanPropertyNamesLength; j++ ) {
            	cell = row.createCell(j);
            	cell.setCellStyle(this.getContentCellStyle(wb));  
            	if(beanPropertyNames[j].contains(".")){
            	 Object value = this.getPropertyValue(currentObj, beanPropertyNames[j]);
                    this.getCellSetValue(cell, value);
            	}else{
            	 List list = (List)map.get(beanPropertyNames[j]);
            	 Object value = list.get(i);
                    this.getCellSetValue(cell, value);
            	}
            }
        }
        
        if(null!=lastRowContent){
        	//填入lastRowContent指定的內容
            int lastRowContentLength = lastRowContent.length;
    	 for(int last=0; last<lastRowContentLength; last++){
    	 String target = lastRowContent[last];
    	 String[] contents = target.split("\\|");
    	 int startCol = Integer.parseInt(contents[0]);
    	 int endCol = Integer.parseInt(contents[1]);
    	 String content = contents[2];
    	 int lastRow = sheet.getLastRowNum()+2;
    	 row = sheet.createRow(lastRow);
    	 cell = row.createCell(startCol);
    	 cell.setCellValue(content);
    	 sheet.addMergedRegion(new CellRangeAddress(lastRow,lastRow,startCol,endCol-1));
    	 }
        }
        
        //將輸出流轉化爲輸入流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        wb.write(out);
      	return new ByteArrayInputStream(out.toByteArray());
} 

/**
* 設置單元格值
* @param cell
* @param value
*/
private void getCellSetValue(Cell cell, Object value){
if(null==value||"".equals(value)){
cell.setCellValue("");
}else{
String type = value.getClass().toString().toLowerCase();
       if(type.endsWith("integer")){
       	cell.setCellValue((Integer)value);
       }else if(type.endsWith("double")){
       	cell.setCellValue((Double)value);
       }else if(type.endsWith("timestamp")){
       	cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(value).toString());
       }else{
       	String val = (String)value;
       	Pattern pattern = Pattern.compile("<\\w*\\s*/?>");
       	Matcher matcher = pattern.matcher(val);
       	String v = matcher.replaceAll("");
       	//將結束符號替換爲:。
       	pattern = Pattern.compile("</\\w*\\s*/?>");
       	matcher = pattern.matcher(v);
       	v = matcher.replaceAll("");
       	cell.setCellValue(v);
       }  
}
}

/**
* 得到bean對象中對應屬性的值
* @param obj
* @param propertyName
* @return
*/
private Object getPropertyValue(Object obj,String beanPropertyName){
final String[] property = beanPropertyName.split(","); 
final String[] beanNameAndPropertyName = property[0].split("\\.");
final String beanName = beanNameAndPropertyName[0].toLowerCase();
final String propertyName = beanNameAndPropertyName[1];
Object value = "";
Method met = null;
        
//關聯查詢
if(obj.getClass().isArray()){
int objLength = Array.getLength(obj);
Object[] currentObjectArray = (Object[])obj;
for(int j=0;j<objLength;j++){
Object currentObject = currentObjectArray[j]; 
String currentObjectBeanName = currentObject.getClass().getSimpleName().toLowerCase();
if(currentObjectBeanName.equals(beanName)){
try {
met = currentObject.getClass().getMethod(this.getterMethodName(propertyName));
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
try {
value = met.invoke(currentObject);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} 
}
}	              
}else{
//屬性的形式爲:	對象.屬性 
if(beanNameAndPropertyName.length>1){
try {
met = obj.getClass().getMethod(this.getterMethodName(propertyName));
} catch (SecurityException e1) {
e1.printStackTrace();
} catch (NoSuchMethodException e1) {
e1.printStackTrace();
}
try {
value = met.invoke(obj);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} 
}else{
//屬性的形式爲:	屬性
try {
met = obj.getClass().getMethod(this.getterMethodName(property[0]));
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}  
           try {
value = met.invoke(obj);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}	  
}

//狀態值替換
if(property.length>1){
value = this.replaceValue(property, value);
}

return value;
}

/**
* 根據內容來替換對應的狀態值
* @param propertyContent
* @param value
* @return
*/
private Object replaceValue(String[] propertyContent, Object value){
int len = propertyContent.length;  
if(null==value) return "";
String name = value.getClass().getSimpleName().toLowerCase();
for(int i=1;i<len;i++){
String[] statusValueAndReplaceValue = propertyContent[i].split(":");
if("integer".equals(name)&&Integer.parseInt(statusValueAndReplaceValue[0])==(Integer)value){
value = statusValueAndReplaceValue[1];
break;
}
}
return value;
}

/**
* 根據屬性名字得到對應的bean對象的getter名字
* @param beanPropertyName	bean對象的屬性名字
* @return
*/
private String getterMethodName(String beanPropertyName){
String name = "get"+beanPropertyName.substring(0, 1).toUpperCase()+beanPropertyName.substring(1);
return name;
}

/**
* 根據屬性名字得到對應的bean對象的setter名字
* @param beanPropertyName	bean對象的屬性名字
* @return
*/
private String setterMethodName(String beanPropertyName){
String name = "set"+beanPropertyName.substring(0, 1).toUpperCase()+beanPropertyName.substring(1);
return name;
}

/**
* 標題樣式
* @param wb
* @return
*/
private CellStyle getTitleCellStyle(Workbook wb){
        Font titleFont = wb.createFont();
        titleFont.setFontHeightInPoints((short)15);
        CellStyle style = createBorderedStyle(wb);
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
        style.setFont(titleFont);
        style.setWrapText(true);
        return style;
}

/**
* 表頭樣式
* @param wb
* @return
*/
private CellStyle getHeaderCellStyle(Workbook wb){
        Font headerFont = wb.createFont();
        headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
        CellStyle style = createBorderedStyle(wb);
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        style.setFont(headerFont);
        style.setWrapText(true);
        return style;
}

/**
* 單元格邊框樣式
* @param wb
* @return
*/
private CellStyle createBorderedStyle(Workbook wb){
        CellStyle style = wb.createCellStyle();
        style.setBorderRight(CellStyle.BORDER_THIN);
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderBottom(CellStyle.BORDER_THIN);
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderLeft(CellStyle.BORDER_THIN);
        style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderTop(CellStyle.BORDER_THIN);
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());
        return style;
    }

/**
* 內容部分單元格樣式
* @param wb
* @return
*/
private CellStyle getContentCellStyle(Workbook wb){
CellStyle style = createBorderedStyle(wb);
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setWrapText(true);
        return style;
}


public String getFileName() {
return fileName;
}


public void setFileName(String fileName) {
this.fileName = fileName;
}


public ICommonService getCommonService() {
return commonService;
}


public void setCommonService(ICommonService commonService) {
this.commonService = commonService;
}


public Map getDownExcelAttrsMap() {
return downExcelAttrsMap;
}


public void setDownExcelAttrsMap(Map downExcelAttrsMap) {
this.downExcelAttrsMap = downExcelAttrsMap;
}
}
相關文章
相關標籤/搜索