`
nenyalanye_1
  • 浏览: 49379 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

jxl导出excel文件的例子,用了java反射

    博客分类:
  • java
阅读更多
最近看了下java的反射内容,自己大概有了一点点概念。主要学习了 Method 和 Field对象的基本用法。所以用反射做了个导出。主要作用是把list列表里的对象的属性与要导出的属性对应上,在业务层我们只需要放入对象集合。和一定的简单规则那么就可以生成相应的excel文件。考虑的不好的地方请各位指出
转换类:
public class CommunUtil {
     //将对象转换为 Map
    public static Map getMap(Object obj) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {

          Map objectMsp = new HashMap();
          //获得对象的类型
          Class classType = obj.getClass();
          //通过构造方法创建一个对象
          Object objCopy = classType.getConstructor(new Class[]{}).newInstance(new Object[]{});

          Field[]  fields = classType.getDeclaredFields();
          for(int i=0;i<fields.length;i++){
              Field field = fields[i];
              String fieldName = field.getName();//获得属性名称
              //getXXX 和 setXXX 方法
              String getMethodName = "get" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);
              Method getMethod = classType.getDeclaredMethod(getMethodName,new Class[]{});
              Object value =   getMethod.invoke(obj,new Object[]{});
              objectMsp.put(fieldName,value);
              //设置对象 相应的属性的值
          }
          return  objectMsp;
      }

    //复制一个对象
     public static Object getObject(Object obj) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {

          Map objectMsp = new HashMap();
          //获得对象的类型
          Class classType = obj.getClass();
          //通过构造方法创建一个对象
          Object objCopy = classType.getConstructor(new Class[]{}).newInstance(new Object[]{});
          Field[]  fields = classType.getDeclaredFields();
          for(int i=0;i<fields.length;i++){
              Field field = fields[i];
              String fieldName = field.getName();//获得属性名称

              //getXXX 和 setXXX 方法
              String getMethodName = "get" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);
              String setMethodName =  "set" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);

              Method getMethod = classType.getDeclaredMethod(getMethodName,new Class[]{});
              Method setMethod = classType.getDeclaredMethod(setMethodName,new Class[]{field.getType()});

              Object value =   getMethod.invoke(obj,new Object[]{});
           // System.out.println("fieldName : " + value + field.getType());
              //设置对象 相应的属性的值
              setMethod.invoke(objCopy,new Object[]{value});

          }
          return  objCopy;
      }
}

规则类:
public abstract class Rules implements Serializable {

   // StreamTokenizer  streamTokenizer =
    protected List[] rowTitle;
    protected Map<String,String> rowMap;
    protected List cols;

    protected Map<Integer,String> rMap;

    public Map<Integer, String> getRMap() {
        return rMap;
    }

    public void setRMap(Map<Integer, String> rMap) {
        this.rMap = rMap;
    }

    public Rules(){
        rMap = new HashMap<Integer,String>();
       rowMap  =  new HashMap<String,String>();
       cols = new ArrayList();
       this.init();
    }

    public Rules(Map<String,String> r){
        rMap = new HashMap<Integer,String>();
        this.rowMap = r;
        cols = new ArrayList();
        this.init();
    }
    public abstract void init();

    public List[] getRowTitle() {
        return rowTitle;
    }

    public void setRowTitle(List[] rowTitle) {
        this.rowTitle = rowTitle;
    }

    public abstract void setRowTitle();

    public Map<String, String> getRowMap() {
        return rowMap;
    }

    public void setRowMap(Map<String, String> rowMap) {
        this.rowMap = rowMap;
    }

    public List getCols() {
        return cols;
    }

    public void setCols(List cols) {
        this.cols = cols;
    }
}

具体规则类
public class UserRules extends Rules {
    public void init() {
        //To change body of implemented methods use File | Settings | File Templates.
        //初始化时设置相应的字段
         this.rMap.put(new Integer(rMap.size()),"userName");
         this.rMap.put(new Integer(rMap.size()),"userAddress");
         this.rMap.put(new Integer(rMap.size()),"userAge");
         this.rMap.put(new Integer(rMap.size()),"clickCount");
         this.rMap.put(new Integer(rMap.size()),"userLong");
        this.rMap.put(new Integer(rMap.size()),"userSalary");
       //  this.rMap.put(new Integer(rMap.size()),"userMount");
        this.setRowTitle();
    }

    //设置标题格式
    public void setRowTitle() {
        //To change body of implemented methods use File | Settings | File Templates.
        this.rowTitle = new List[2];
        List  rList = new ArrayList();
        rList.add(new String[]{"用户姓名","1","0"});
        rList.add(new String[]{"用户地址","0","1"});
        rList.add(new String[]{"用户年龄","0","1"});
        rList.add(new String[]{"大列标题","1","1"});

        this.rowTitle[0] = rList;
        List  rList2  = new ArrayList();
        rList2.add(new String[]{"用户姓名","0","0"});
        rList2.add(new String[]{"点击数","0","0"});
        rList2.add(new String[]{"总数","0","0"});
        rList2.add(new String[]{"工资","0","0"});
        rList2.add(new String[]{"用户数量","0","0"});
      //  rList2.add(new String[]{"大列标题1","0","0"});
     //   rList2.add(new String[]{"大列标题2","0","0"});
      //  rList.add(new String[]{"大列标题","0","0"});
        this.rowTitle[1] = rList2;
    }
}


vo对象类
public class User {
     private String userName;
    private String userAddress;
    private int userAge;
    private int clickCount;
    private long  userLong;
    private String userSalary;
    private String userMount;
    public String getUserName() {
    return userName;
}

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserAddress() {
        return userAddress;
    }

    public void setUserAddress(String userAddress) {
        this.userAddress = userAddress;
    }

    public int getUserAge() {
        return userAge;
    }

    public void setUserAge(int userAge) {
        this.userAge = userAge;
    }

    public int getClickCount() {
        return clickCount;
    }

    public void setClickCount(int clickCount) {
        this.clickCount = clickCount;
    }

    public long getUserLong() {
        return userLong;
    }

    public void setUserLong(long userLong) {
        this.userLong = userLong;
    }

    public String getUserSalary() {
        return userSalary;
    }

    public void setUserSalary(String userSalary) {
        this.userSalary = userSalary;
    }

    public String getUserMount() {
        return userMount;
    }

    public void setUserMount(String userMount) {
        this.userMount = userMount;
    }
}


测试类:
public class ExcelWriter {
    public static void main(String [] args){
//        Date d1 = new Date(System.currentTimeMillis()-604800000L);
//        Date d2 = new Date();
//        System.out.println(d1+"\n" + d2);
        ExcelWriter writer = new ExcelWriter();
        List userList = new ArrayList();
        for(int i=0;i<10;i++){
                User user = new User();
                user.setClickCount(1+i);
                user.setUserAddress("userAddress" + i);
                user.setUserAge(20+i);
                user.setUserLong(new Long(10000)+i);
                user.setUserMount("userMount" + i);
                user.setUserName("userName" + i);
                user.setUserSalary("userSalary" + i);
                userList.add(user);
           }
        try {
            writer.exportExcel(userList); //导出文件
            UserRules ur = new  UserRules();
            writer.exportExcel(userList,ur);
        } catch (InvocationTargetException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (NoSuchMethodException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (InstantiationException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IllegalAccessException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (WriteException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }

    //设置标题
    public void exportExcel(List list,Rules rules) throws IOException, WriteException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        List[]  rowList =   rules.getRowTitle();
        Label lable = null;
        File file = new File("e:\\mytest\\testjxl3.xls");
        WritableWorkbook workbook  = Workbook.createWorkbook(file);
        WritableSheet sheet = workbook.createSheet("TestCreateExcel", 0);
        Map rMap = rules.getRMap(); //得到字段信息
        //处理标题
        int i=0; //记录行数
        for(;i<rowList.length;i++){
             List row = rowList[i];
            for(int cop=0, j=0;j<row.size();cop++,j++){ //得到每列标题的信息 包括跨行和跨列的信息
                String [] title = (String[]) row.get(j);
                String ctitle = title[0];
                lable = new Label(cop,i,ctitle);
                sheet.addCell(lable);
                int r = Integer.parseInt(title[1]);
                int c = Integer.parseInt(title[2]) ;
                if( r != 0 || c != 0){ //合并单元格
                   sheet.mergeCells(cop,i,cop+c,r+i);
                    cop += c;
                }
            }
        }
       //处理要导出的数据
       List cols = rowList[rowList.length-1]; //得到要导出的列的信息
       int rowCount = list.size() + rowList.length; //总行数
       if( list != null && list.size()>0){
           for(int n=0;n<list.size();n++){
                Map objectMap = CommunUtil.getMap( list.get(n)); //将对象转换成 == Map
                for(int k=0;k<rMap.size();k++){
                    Object   key   =  rMap.get(new Integer(k));
                    String  columnValue =  (objectMap.get(key)+"").trim();
                    lable = new Label(k,n+rowList.length,columnValue);
                    sheet.addCell(lable);
                }
           }
       }
       workbook.write();
       workbook.close();


    }

    public void exportExcel(List list) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
               File file = new File("e:\\mytest\\testjxl2.xls");
               try {
                   System.out.println("=======开始============");
                   WritableWorkbook workbook  = Workbook.createWorkbook(file);
                   WritableSheet sheet = workbook.createSheet("TestCreateExcel", 0);

                   //一些临时变量,用于写到excel中
                   Label l = null;
                   jxl.write.Number n = null;
                   jxl.write.DateTime d = null;

                  //预定义的一些字体和格式,同一个Excel中最好不要有太多格式
                   WritableFont headerFont = new WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD,
                           false, UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLUE);
                   WritableCellFormat headerFormat = new WritableCellFormat(headerFont);

                   WritableFont titleFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD,
                           false, UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.RED);
                   WritableCellFormat titleFormat = new WritableCellFormat(titleFont);

                   WritableFont detFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD,
                           false, UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK);
                   WritableCellFormat detFormat = new WritableCellFormat(detFont);

                   NumberFormat nf = new NumberFormat("0.00000"); //用于Number的格式
                   WritableCellFormat priceFormat = new WritableCellFormat(detFont, nf);

                   DateFormat df = new DateFormat("yyyy-MM-dd");//用于日期的
                   WritableCellFormat dateFormat = new WritableCellFormat(detFont, df);

                   //设置标题
                   l = new Label(0, 0, "指标", headerFormat);
                   sheet.addCell(l);
                   sheet.mergeCells(0, 0, 0, 1); //合并0到3列 0到0行  4个参数是 c,r,c,r

                   l = new Label(1,0,"总用户", headerFormat);
                   sheet.addCell(l);
                   sheet.mergeCells(1, 0, 2, 0);

                    l = new Label(3,0,"ADSL绑定用户", headerFormat);
                    sheet.addCell(l);
                    sheet.mergeCells(3, 0, 4, 0);

                    l = new Label(5,0,"互联星空用户", headerFormat);
                    sheet.addCell(l);
                    sheet.mergeCells(5, 0, 6, 0);


                    //跨列后 列索引从跨的那行开始
                    l = new Label(1, 1, "访问量", headerFormat);
                    sheet.addCell(l);

                    l = new Label(2, 1, "点击量", headerFormat);
                    sheet.addCell(l);

                    l = new Label(3, 1, "访问量", headerFormat);
                    sheet.addCell(l);

                    l = new Label(4, 1, "点击量", headerFormat);
                    sheet.addCell(l);

                    l = new Label(5, 1, "访问量", headerFormat);
                    sheet.addCell(l);

                    l = new Label(6, 1, "点击量", headerFormat);
                    sheet.addCell(l);



                    if(list != null && list.size()>0){
                        for(int i=0;i<list.size();i++){
                          Map objectMap = CommunUtil.getMap( list.get(i)); //将对象转换成 == Map
                             int j=0;//列从第一列开始
                             for(Object o : objectMap.keySet()){
                                //String key = (String) o;
                                 String pvalue =  objectMap.get(o)+"".trim();
                                 //System.out.println("pvalue== " + pvalue);
                                 //System.out.println("userValue"+i+"   "+o+"   " + objectMap.get(o));
                                 Label  lb = new Label(j,i+2,pvalue);
                                 sheet.addCell(lb);
                                 j++;
                             }
                       }
                    }

                   workbook.write();
                   workbook.close();
                  System.out.println("====================结束=====================");

               } catch (IOException e) {
                   e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
               } catch (RowsExceededException e) {
                   e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
               } catch (WriteException e) {
                   e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
               }

    }
}


下面是整个工程   我是用idea做的  可能和eclipse有冲突。。
  • jxl.jar (430.4 KB)
  • 下载次数: 34
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics