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

你可能感兴趣的:(POI操作Excel导入导出)