反射--小念頭

目錄

將一個類中的屬性值全部拿到,

public class MoneyOpJsonVo {

    public static String os1="崗位津貼";
    public static String os2="補貼"; 

    public static List<String> getBaseSalaryList(){
        List<String> resultList=new ArrayList<>();
        try {
            MoneyOpJsonVo model=new MoneyOpJsonVo();
            Field fields[]=model.getClass().getDeclaredFields();
            String[] name=new String[fields.length];
            Object[] value=new Object[fields.length];
            Field.setAccessible(fields, true);
            for (int i = 0; i < name.length; i++) {
                name[i] = fields[i].getName();
                value[i] = fields[i].get(model);
                resultList.add((String)value[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultList;
    }
    }

在service裏面調用一個dao 的所有

    @Autowired
    private ComplexDao complexDao;
    @Override
    public Object complexQuery(String type)throws Exception {
        Class  clazz=complexDao.getClass();
        String methondName = EnumUtil.code2Desc(DemoEnum.class, type); 
        //  或者 Method [] methods=clazz.getMethods(); 
        Method method= clazz.getMethod(methondName,String.class);
        Object obj1 = method.invoke(complexDao,"demo");
        System.out.println(JsonUtil.toJson(obj1));
        return obj1;
    }
public enum DemoEnum implements IDemoEnum<DemoEnum> {
    RPC_12("1","queryNameIsNull"),
    RPC_13("2","queryNameIsNotNull"),
    RPC_14("3","queryDateSection"),
    RPC_15("4","queryNameLike"),
    RPC_16("5","queryIdNotEq"),
    RPC_17("6","getInTelAndValid"),
    RPC_18("7","addBySql"),}

利用自定義的註解把 model 的屬性寫入到 excel中,註解的value對應excel的第一列的列名

package com.fang.jin.util;


import com.fang.jin.bo.FangItemExport;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

@Component
public class ExcelManageUtil {
    public  static  <T> ByteArrayInputStream writeDataToExcels( List<FangItemExport> insertDatas) throws Exception {
        //創建workbook
        Workbook workBook = new XSSFWorkbook();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = null;
        Sheet sheet = workBook.createSheet("sheet");

        CellStyle style = workBook.createCellStyle();
        style.setAlignment(HorizontalAlignment.LEFT); // 想左靠齊
        // 創建標題
        int rowIndex = 0;
        int colIndex = 0;
        Row row = sheet.createRow(rowIndex);
        List<String> titles = new ArrayList<>();
        titles.add("用戶id");
        titles.add("客戶名字");
        titles.add("銷售名稱");
        titles.add("電話");
        for (String title : titles) {
            row.createCell(colIndex, Cell.CELL_TYPE_STRING).setCellValue(title);
            colIndex++;
        }
        try {
            for (FangItemExport t : insertDatas) {
                rowIndex++;
                row = sheet.createRow(rowIndex); // 第二行開始插入數據
                row.createCell(0).setCellValue(t.getId());
                row.createCell(1).setCellValue(t.getName());
                row.createCell(2).setCellValue(t.getUsername());
                row.createCell(3).setCellValue(t.getTel());
            }
            workBook.write(out);
            byte[] b = out.toByteArray();
            in = new ByteArrayInputStream(b);
        } catch (Exception e) {

        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return in;
    }




    public  static  <T> ByteArrayInputStream writeToExcels( List<T> insertDatas) throws Exception {
        //創建workbook
        Workbook workBook = new XSSFWorkbook();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = null;
        Sheet sheet = workBook.createSheet("sheet");

        CellStyle style = workBook.createCellStyle();
        style.setAlignment(HorizontalAlignment.LEFT); // 想左靠齊
        // 創建標題
        int rowIndex = 0;
        int colIndex = 0;
        Row row = sheet.createRow(rowIndex);
        List<String> titles = getTitleList(insertDatas.get(0));
        for (String title : titles) {
            row.createCell(colIndex, Cell.CELL_TYPE_STRING).setCellValue(title);
            colIndex++;
        }
        try {
            for (T t : insertDatas) {
                rowIndex++;
                row = sheet.createRow(rowIndex); // 第二行開始插入數據
                List<Field> fields =getFieldList(t.getClass());
                for (Field field : fields) {
                    FieldName indexFieldName=field.getAnnotation(FieldName.class);
                    colIndex=getColIndex(titles,indexFieldName.name());
                    if(colIndex==-1){
                        continue;
                    }
                    String fieldName = field.getName();
                    String getMethodName =getMethodName(fieldName);
                    Method method = t.getClass().getMethod(getMethodName);
                    Object val = method.invoke(t);
                    String textVal = val != null?String.valueOf(val):"";
                    row.createCell(colIndex, Cell.CELL_TYPE_STRING).setCellValue(textVal);
                    row.setHeightInPoints(30);
                }
            }
            workBook.write(out);
            byte[] b = out.toByteArray();
            in = new ByteArrayInputStream(b);
        } catch (Exception e) {

        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return in;
    }


    public static <T> List<String>  getTitleList(T t){
        List<String> fieldlist=new ArrayList<>();
        List<Field> fields =getFieldList(t.getClass());
        for (Field field : fields) {
            FieldName indexFieldName=field.getAnnotation(FieldName.class);
            if(indexFieldName!=null){
                fieldlist.add(indexFieldName.name());
            }
        }
        return fieldlist;
    }



    public static Integer getColIndex(List<String> titleRow ,String fieldName){
        for(int i=0;i<titleRow.size();i++){
            if(titleRow.get(i).equals(fieldName)){
                return i;
            }
        }
        return -1;
    }


    private static String getMethodName(String fildeName) throws Exception{
        byte[] items = fildeName.getBytes();
        items[0] = (byte) ((char) items[0] - 'a' + 'A');
        return "get"+new String(items);
    }


    public static List<Field> getFieldList(Class<?> clazz){
        if(null == clazz){
            return null;
        }
        List<Field> fieldList = new LinkedList<>();
        Field[] fields = clazz.getDeclaredFields();
        for(Field field : fields){
            fieldList.add(field);
        }
        return fieldList;
    }



}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章