excel通用模板组件

最近在公司实习时,项目中总遇到excel表的导出,就产生写一个组件实现此功能的想法,在此感谢MaximusGet的帮助,基于jdk1.5元数据注解、注释来实现属性名、列名解耦合,模板组件化,或者可以通过LinkedHashMap实现

 

 

Java代码 
  1. package cn.edu.yxy.bean;  
  2.   
  3. import java.lang.annotation.Documented;  
  4. import java.lang.annotation.ElementType;  
  5. import java.lang.annotation.Retention;  
  6. import java.lang.annotation.RetentionPolicy;  
  7. import java.lang.annotation.Target;  
  8.   
  9.   
  10. /** 
  11.  * @author  杨新彦 
  12.  * @ 时间     2012-2-2  
  13.  * @ 状态     创建 
  14.  */  
  15. @Documented  
  16. @Retention(RetentionPolicy.RUNTIME)  
  17. @Target(ElementType.FIELD)  
  18. public @interface ExcelAnnotation {  
  19.     public int id() default 0;//excel列id  
  20.     public String name();   //excel列名  
  21. }  

 列名显示顺序比较

Java代码 
  1. package cn.edu.yxy.util;  
  2.   
  3. import java.lang.reflect.Field;  
  4. import java.util.Comparator;  
  5.   
  6. import cn.edu.yxy.bean.ExcelAnnotation;  
  7.   
  8.   
  9. /** 
  10.  * @author  杨新彦 
  11.  * @ 时间     2012-2-2  
  12.  * @ 状态     创建 
  13.  */  
  14. public class FieldComparator implements Comparator<Object> {  
  15.   
  16.     public int compare(Object arg0, Object arg1) {  
  17.         Field fieldOne = (Field)arg0;  
  18.         Field fieldTwo = (Field)arg1;  
  19.         ExcelAnnotation annoOne = fieldOne.getAnnotation(ExcelAnnotation.class);  
  20.         ExcelAnnotation annoTwo = fieldTwo.getAnnotation(ExcelAnnotation.class);  
  21.         if(annoOne==null||annoTwo==null){  
  22.             return 0;  
  23.         }  
  24.         int result = annoOne.id()-annoTwo.id();  
  25.         if(result>0){  
  26.             return 1;  
  27.         }else if(result<0){  
  28.             return -1;  
  29.         }else {  
  30.             return 0;  
  31.         }  
  32.     }  
  33.   
  34. }  

 //通用组件

Java代码 
  1. package cn.edu.yxy.util;  
  2.   
  3. import java.io.File;  
  4.   
  5. /** 
  6.  * @author  杨新彦 
  7.  * @ 时间     2012-2-2  
  8.  * @ 状态     创建 
  9.  */  
  10. public class DataToExcelModel {  
  11.       
  12.     private static int sheetCount = 0;  
  13.     private static int max = 0;  
  14.     private static List<String> columnArr = null// 属性名集合  
  15.     private static List<Method> methodArr = null// 待打印属性的get方法  
  16.       
  17.     /** 
  18.      *  
  19.      * @param source    数据源 
  20.      * @param className 实体类类名 
  21.      * @param path      文件存放路径 
  22.      * @return  true:执行成功;false:执行失败 
  23.      * @throws Exception 
  24.      */  
  25.     @SuppressWarnings("all")  
  26.     public static boolean createExcel(List source,String className,String path,final int pageCount) throws Exception {  
  27.         HSSFWorkbook wb = new HSSFWorkbook();  
  28.         if(null != source){  
  29.             max = source.size();    //总记录数  
  30.             sheetCount = max / pageCount + (max % pageCount == 0 ? 0 : 1);  //总页数  
  31.         }else{  
  32.             return createFile(path, wb);  
  33.         }  
  34.         Class classEntity = null;  
  35.         try {  
  36.             classEntity = Class.forName(className);  
  37.         } catch (ClassNotFoundException e) {  
  38.             e.printStackTrace();  
  39.         }  
  40.         //排序对应的属性名  
  41.         Field[] arrField = sortArributeName(classEntity);  
  42.         //生成方法集合并缓存  
  43.         createMethod(arrField, classEntity);  
  44.         // 生成对应的方法名,要打印的列名  
  45.         int nameSize = arrField.length;  
  46.         for (int i = 0; i < sheetCount; i++) {  
  47.             HSSFSheet sheet = wb.createSheet("sheet" + i);  
  48.             HSSFRow row = sheet.createRow(0);  
  49.             HSSFCell cell = null;  
  50.             int begin = pageCount * (i);  
  51.             //打印表头  
  52.             for (int j = 0; j < nameSize; j++) {  
  53.                 cell = row.createCell((short) j);  
  54.                 cell.setEncoding(HSSFCell.ENCODING_UTF_16);  
  55.                 cell.setCellValue(columnArr.get(j));  
  56.             }  
  57.               
  58.             int k = 0;  
  59.             while (k < pageCount && (begin + k < max)) {  
  60.                 Object object = source.get(begin + k);  
  61.                 row = sheet.createRow(k + 1);  
  62.                 for (int m = 0; m < nameSize; m++) {  
  63.                     cell = row.createCell((short) m);  
  64.                     cell.setEncoding(HSSFCell.ENCODING_UTF_16);  
  65.                     try {  
  66.                         cell.setCellValue(null == ((methodArr.get(m)).invoke(object)) ? "" : (methodArr.get(m)).invoke(object).toString());  
  67.                     } catch (Exception e) {  
  68.                         e.printStackTrace();  
  69.                     }  
  70.                 }  
  71.                 k++;  
  72.             }  
  73.         }  
  74.         return createFile(path,wb);  
  75.     }  
  76.       
  77.     private static  void createMethod(Field[] arrField,Class<?> classEntity){  
  78.         String columnName; // 打印的列�  
  79.         String beanName; // 属性名  
  80.         String methodName; // 方法名  
  81.         columnArr = new ArrayList<String>(); // 属性名集合  
  82.         methodArr = new ArrayList<Method>();  
  83.         for (Field field : arrField) {  
  84.             ExcelAnnotation ann = field.getAnnotation(ExcelAnnotation.class);  
  85.             columnName = ann.name();  
  86.             columnArr.add(columnName);  
  87.             beanName = field.getName();  
  88.               
  89.             StringBuffer sb = new StringBuffer();  
  90.             sb.append("get");  
  91.             sb.append(beanName.substring(01).toUpperCase());  
  92.             sb.append(beanName.substring(1));  
  93.               
  94.             methodName = sb.toString();  
  95.             Method method = null;  
  96.             try {  
  97.                 method = classEntity.getMethod(methodName);  
  98.             } catch (Exception e) {  
  99.                 e.printStackTrace();  
  100.             }  
  101.             methodArr.add(method);  
  102.         }  
  103.     }  
  104.       
  105.     /** 
  106.      * 生成文件,存放在制定的路径 
  107.      * @param path  路径 
  108.      * @param wb    HSSFWorkbook 
  109.      * @return  true 执行成功 
  110.      * @throws IOException 
  111.      */  
  112.     private static  boolean createFile(String path,HSSFWorkbook wb){  
  113.         boolean flag = false;  
  114.         //判断文件是否存在,若存在删除  
  115.         File file = new File(path);  
  116.         if(file.exists()){  
  117.             file.delete();  
  118.         }  
  119.         FileOutputStream out = null;  
  120.         try {  
  121.             out = new FileOutputStream(path);  
  122.             wb.write(out);  
  123.             flag = true;  
  124.         } catch (Exception e) {  
  125.             e.printStackTrace();  
  126.         }finally{  
  127.             try {  
  128.                 out.close();  
  129.             } catch (IOException e) {  
  130.                 e.printStackTrace();  
  131.             }  
  132.         }  
  133.         return flag;  
  134.     }  
  135.       
  136.     /** 
  137.      * 排序表头 
  138.      * @param classEntity 
  139.      * @return 
  140.      */  
  141.     private static Field[] sortArributeName(Class<?> classEntity){  
  142.         // 对需要打印的属性名排序  
  143.         Field[] fields = classEntity.getDeclaredFields();  
  144.         ArrayList<Field> arrFieldList = new ArrayList<Field>();  
  145.         for (Field field : fields) {  
  146.             if (field.isAnnotationPresent(ExcelAnnotation.class)) {  
  147.                 arrFieldList.add(field);  
  148.             }  
  149.         }  
  150.         Field[] arrField = {};  
  151.         arrField = arrFieldList.toArray(arrField);  
  152.         //排序显示  
  153.         Arrays.sort(arrField, new FieldComparator());  
  154.         return arrField;  
  155.     }  
  156. }  

 javabean信息

Java代码 
  1. package cn.edu.yxy.bean;  
  2.   
  3.   
  4. /** 
  5.  * @author  杨新彦 
  6.  * @ 时间     2012-2-2  
  7.  * @ 状态     创建 
  8.  */  
  9. public class DepartmentBean {  
  10.       
  11.     public DepartmentBean() {  
  12.         super();  
  13.     }  
  14.       
  15.     /** 
  16.      * id<br> 
  17.      * 单位id 
  18.      */  
  19.     private long id;  
  20.   
  21.     /** 
  22.      * name<br> 
  23.      * 单位名称 
  24.      */  
  25.     @ExcelAnnotation(id = 8,name = "单位名称")  
  26.     private String name;  
  27.       
  28.     /** 
  29.      * code<br> 
  30.      * 单位编码 
  31.      */  
  32.     @ExcelAnnotation(id = 2,name = "单位编码")  
  33.     private String code;  
  34.         // get、set方法  
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值