java导出Excel的工具分享

来源:互联网 发布:返利网 淘宝taosave 编辑:程序博客网 时间:2024/05/23 15:25

介绍一下本工具的功能: 对于给定的java对象(List)生成一个excell文件。

 

在这个list里面的每个子对象带有特定的列注释(此注释写在set方法上,思考了下其实这个注释最好能写在get方法上),开发时需要导入POI相关包,

然后对List的对象写一个特定注释的类,比如Student.java,即可调用工具完成excell文件的生成。

 

[java] view plaincopy
  1. import java.util.Date;  
  2.   
  3. import Excel.annotation.Column;  
  4. import XMLHandler.xmlopt.annotation.Node;  
  5. import XMLHandler.xmlopt.annotation.Xml;  
  6. import XMLHandler.xmlopt.annotation.Attr;  
  7.   
  8. @Xml(name="Student")  
  9. public class Student {  
  10.   
  11.     private String id;   
  12.       
  13.     private String name;   
  14.       
  15.     private String bir;  
  16.       
  17.     private String  age;  
  18.   
  19.     public String getId() {  
  20.         return id;  
  21.     }  
  22.   
  23.     @Column(name="学号")  
  24.     public void setId(String id) {  
  25.         this.id = id;  
  26.     }  
  27.   
  28.     public String getName() {  
  29.         return name;  
  30.     }  
  31.   
  32.     @Column(name="姓名")  
  33.     public void setName(String name) {  
  34.         this.name = name;  
  35.     }  
  36.   
  37.     public String getBir() {  
  38.         return bir;  
  39.     }  
  40.   
  41.     @Column(name="出生日期")  
  42.     public void setBir(String bir) {  
  43.         this.bir = bir;  
  44.     }  
  45.   
  46.     public String getAge() {  
  47.         return age;  
  48.     }  
  49.   
  50.     @Column(name="年龄")  
  51.     public void setAge(String age) {  
  52.         this.age = age;  
  53.     }  
  54.       
  55.       
  56.       
  57. }  

 

用到的注释类Column.java,

[java] view plaincopy
  1. import java.lang.annotation.Documented;  
  2. import java.lang.annotation.ElementType;  
  3. import java.lang.annotation.Inherited;  
  4. import java.lang.annotation.Retention;  
  5. import java.lang.annotation.RetentionPolicy;  
  6. import java.lang.annotation.Target;  
  7.   
  8. /** 
  9.  * @desc: 描述excell文件的列头信息  *   
  10.  * @date-2011-1-10 
  11.  * @author ziliang 
  12.  */  
  13. @Target(ElementType.METHOD)  
  14. @Retention(RetentionPolicy.RUNTIME)  
  15. @Documented  
  16. @Inherited  
  17. public @interface Column {  
  18.       
  19.     /** 
  20.           * 列名注释 
  21.      */  
  22.     public String name() default "";  
  23.       
  24.   
  25. }  

 

下面看我们主要的工具类,

 

[java] view plaincopy
  1. import java.io.*;  
  2. import java.lang.reflect.InvocationTargetException;  
  3. import java.lang.reflect.Method;  
  4. import java.util.*;  
  5.   
  6. import org.apache.poi.hssf.usermodel.HSSFCell;  
  7. import org.apache.poi.hssf.usermodel.HSSFCellStyle;  
  8. import org.apache.poi.hssf.usermodel.HSSFFont;  
  9. import org.apache.poi.hssf.usermodel.HSSFRow;  
  10. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  11. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  12.   
  13. import Excel.annotation.Column;  
  14. import XMLHandler.xmlopt.annotation.Ignore;  
  15. import XMLHandler.xmlopt.annotation.Xml;  
  16.   
  17.   
  18. /** 
  19.  * @desc: excel操作工具 
  20.  * @date-2011-1-10 
  21.  * @author-ziliang 
  22.  * */  
  23. public class ExcelUtil {  
  24.       
  25.     /** 
  26.      * 待创建的excel文件名,你可以写定名字 
  27.      * */  
  28.     private static  String filename="";  
  29.       
  30.       
  31.       
  32.     /** 
  33.      * @desc 根据list的数据生成excel文件 
  34.      * @author ZILIANG 
  35.      * @throws IOException  
  36.      * */  
  37.     public static void createExcelFile(List list) throws IOException{  
  38.           
  39.         FileOutputStream fileOut=null;  
  40.         if(list.size()==0)return;  
  41.         Object obj=list.get(0);  
  42.         HSSFWorkbook wb=(HSSFWorkbook) getWorkbook(obj);  
  43.         //构造excel头  
  44.         getExcelHead(obj,0,wb);  
  45.         // 产生唯一文件名称,    并关联文件流  
  46.         String file_name=System.currentTimeMillis()+filename+".xls";  
  47.         fileOut = new FileOutputStream(file_name);  
  48.         //循环处理数据行:注意行序号  
  49.         for(int i=1;i<=list.size();i++){  
  50.             obj=list.get(i-1);  
  51.             getExcelBody(obj,i,wb);  
  52.         }  
  53.         wb.write(fileOut);  
  54.         fileOut.close();  
  55.           
  56.     }  
  57.       
  58.       
  59.       
  60.     /** 
  61.      * 获取当前工作薄的每一行数据 
  62.      * */  
  63.     public static void getExcelBody(Object obj,int rowno,HSSFWorkbook wb ) throws IOException{  
  64.           
  65.         Class<?> targetClass = obj.getClass();  
  66.           
  67.         // 创建第一个工作表,命名filename  
  68.         HSSFSheet sheet = wb.getSheet(filename);  
  69.         Method methods[] = targetClass.getMethods();  
  70.         int colno=0;  
  71.         HSSFRow row = sheet.createRow(rowno);  
  72.         for (Method method : methods) {  
  73.             if (!isSetMethod(method))  
  74.                 continue;  
  75.             if (method.getAnnotation(Ignore.class) != null)  
  76.                 continue;  
  77.             //处理数据行  
  78.             HSSFCell cell = row.createCell((short) colno);  
  79.             String defaultNodeName = method.getName().substring(3);  
  80.             Object value = invokeGet(obj, defaultNodeName);   
  81.             if(value==null) value="";  
  82.             cell.setCellValue(value.toString());  
  83.             colno++;  
  84.               
  85.         }  
  86.       
  87.           
  88.     }  
  89.       
  90.       
  91.     /** 
  92.      * 获取当前工作薄的头 
  93.      * */  
  94.     public static void getExcelHead(Object obj,int rowno,HSSFWorkbook wb ) throws IOException{  
  95.           
  96.         Class<?> targetClass = obj.getClass();  
  97.           
  98.         // 创建第一个工作表,命名filename  
  99.         HSSFSheet sheet = wb.getSheet(filename);  
  100.         Method methods[] = targetClass.getMethods();  
  101.         int colno=0;  
  102.         HSSFRow row = sheet.createRow(rowno);  
  103.         for (Method method : methods) {  
  104.             if (!isSetMethod(method))  
  105.                 continue;  
  106.             if (method.getAnnotation(Ignore.class) != null)  
  107.                 continue;  
  108.             Column columnAnno = method.getAnnotation(Column.class);  
  109.             String column=columnAnno.name();  
  110.             if(isNotEmpty(column)&&rowno==0){  
  111.                 //读取注释,处理头信息  
  112.                 HSSFCell cell = row.createCell((short) colno);  
  113.                 cell.setCellValue(column);  
  114.                 cell.setCellStyle(setCellStyle(wb));  
  115.                 colno++;  
  116.             }  
  117.         }  
  118.           
  119.     }  
  120.       
  121.       
  122.     /** 
  123.      * @param 带有特定注释的javabean 
  124.      * @author ziliang 
  125.      * @return HSSFWorkbook,返回创建了一个名为filename的sheet页的工作薄 
  126.      * */  
  127.     public static HSSFWorkbook getWorkbook(Object obj) throws FileNotFoundException{  
  128.           
  129.         Class<?> targetClass = obj.getClass();  
  130.         // 取类注解  
  131.         Xml docAnno = targetClass.getAnnotation(Xml.class);  
  132.         if (docAnno == null) {  
  133.             throw new RuntimeException("被处理的类必须带有annotation的注解");  
  134.         }  
  135.         //取类名字,如名字注释空则取默认类名为excel文件名  
  136.         String file_name = docAnno.name();  
  137.         if (file_name == null || file_name.length() == 0)  
  138.             file_name = obj.getClass().getSimpleName();  
  139.         filename=file_name;  
  140.         HSSFWorkbook wb = new HSSFWorkbook();  
  141.         // 创建一个工作表,命名filename  
  142.         HSSFSheet sheet = wb.createSheet(filename);  
  143.         return wb;  
  144.       
  145.     }  
  146.       
  147.       
  148.     //设置单元样式  
  149.     public static HSSFCellStyle setCellStyle(HSSFWorkbook wb){  
  150.         HSSFFont font = wb.createFont();  
  151.         font.setColor(HSSFFont.COLOR_NORMAL);  
  152.         font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
  153.         HSSFCellStyle cellStyle = wb.createCellStyle();  
  154.         cellStyle.setFont(font);  
  155.         return cellStyle;  
  156.     }  
  157.       
  158.       
  159.       
  160.       
  161.       
  162.     /** 
  163.      * 是否为符合javaBean规范的set方法 
  164.      *  
  165.      * @param methodName 
  166.      * @return 
  167.      */  
  168.     public static boolean isSetMethod(Method method) {  
  169.         String methodName = method.getName();  
  170.         if (!methodName.startsWith("set")) {  
  171.             return false;  
  172.         }  
  173.         Class<?>[] clazzes = method.getParameterTypes();  
  174.         // 如果方法的参数>1 则不是设置属性的方法  
  175.         if (clazzes.length != 1) {  
  176.             return false;  
  177.         }  
  178.         return true;  
  179.     }  
  180.       
  181.       
  182.     //工具函数: 判断字符串不空  
  183.     public static boolean isNotEmpty(String s){  
  184.         return s!=null && !s.trim().equalsIgnoreCase("");  
  185.     }  
  186.       
  187.      //取obj属性值  
  188.     private static Object invokeGet(Object target, String name) {  
  189.         name = name.substring(01).toUpperCase() + name.substring(1);  
  190.         String getMethodName = "get" + name;  
  191.   
  192.         Object res = null;  
  193.         try {  
  194.             Method method = target.getClass().getMethod(getMethodName);  
  195.             res = method.invoke(target);  
  196.         } catch (SecurityException e) {  
  197.             e.printStackTrace();  
  198.         } catch (IllegalArgumentException e) {  
  199.             e.printStackTrace();  
  200.         } catch (NoSuchMethodException e) {  
  201.             e.printStackTrace();  
  202.         } catch (IllegalAccessException e) {  
  203.             e.printStackTrace();  
  204.         } catch (InvocationTargetException e) {  
  205.             e.printStackTrace();  
  206.         }  
  207.         return res;  
  208.     }  
  209.       
  210.       
  211.       
  212.       
  213. }  

上面代码用到了另外2个特别注释类ignore.java和xml.java,参见我的另外文章:xml操作工具-实现篇

 

好了,有了上面完整的代码,下面来测试下student组成的List,生成的excell会是样子的?

 

[java] view plaincopy
  1. import java.io.*;  
  2. import java.util.*;  
  3.   
  4. import org.junit.AfterClass;  
  5. import org.junit.BeforeClass;  
  6. import org.junit.Ignore;  
  7. import org.junit.Test;  
  8.   
  9. import Excel.excelutil.ExcelUtil;  
  10. import XMLHandler.xmlopt.util.XmlUtil;  
  11. import XMLHandler.xmlutil.test.School;  
  12.   
  13. public class TestExcel {  
  14.   
  15.     @BeforeClass  
  16.     public static void setUpBeforeClass() throws Exception {  
  17.     }  
  18.   
  19.     @AfterClass  
  20.     public static void tearDownAfterClass() throws Exception {  
  21.     }     
  22.       
  23.       
  24.     //@Ignore  
  25.     @Test  
  26.     public void testExcel2File() throws FileNotFoundException, IOException {  
  27.           
  28.         List list=new ArrayList();  
  29.         Student s1=new Student();  
  30.         s1.setAge("22");  
  31.         s1.setName("sname");  
  32.         list.add(s1);  
  33.           
  34.         Student s2=new Student();  
  35.         s2.setAge("22");  
  36.         s2.setBir("2010-1-1");  
  37.         list.add(s2);  
  38.           
  39.         Student s3=new Student();  
  40.         s3.setAge("55");  
  41.         s3.setId("001");  
  42.         list.add(s3);  
  43.           
  44.         ExcelUtil.createExcelFile(list);  
  45.   
  46.         System.out.println("");  
  47.   
  48.     }  
  49.       
  50.       
  51.       
  52.   
  53. }  

 

 

 

 

 测试上述代码,生成的excell文件放在工程路径下,文件名为时间戳加上Student构成,例如:1294967658921Student.xls

 

 

本文主要是用POI包实现的

0 0
原创粉丝点击