溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何用注釋解決反射不保證字段的順序

發(fā)布時間:2021-10-14 10:43:04 來源:億速云 閱讀:115 作者:iii 欄目:編程語言

本篇內(nèi)容主要講解“如何用注釋解決反射不保證字段的順序”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學(xué)習(xí)“如何用注釋解決反射不保證字段的順序”吧!

Talk is cheap, show me the code.直接上碼!

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyColumn {

    int columnIndex() default 0;

}
public class PoiUtil {

    /**
     * 獲取文件內(nèi)容列表
     *
     * @param file
     * @param clazz
     * @param <T>
     * @return
     * @throws Exception
     */
    public <T> List<T> getListFromFile(MultipartFile file, Class<T> clazz) throws Exception {
        //最終返回數(shù)據(jù)
        List<T> resultList = new ArrayList<T>();

        InputStream is = file.getInputStream();
        //使用工廠方法創(chuàng)建.
        Workbook wb = WorkbookFactory.create(is);
        Sheet sheet = wb.getSheetAt(0);

        int totalRowNum = sheet.getLastRowNum();
        //獲得總列數(shù)
        int cellLength = sheet.getRow(0).getPhysicalNumberOfCells();
        //獲取反射類的所有字段
        Field[] fields = clazz.getDeclaredFields();
        //創(chuàng)建一個字段數(shù)組,用于和excel行順序一致.
        Field[] newFields = new Field[cellLength];
        for (int i = 0; i < cellLength; i++) {
            for (Field field : fields) {
                Annotation[] annotationArr = field.getDeclaredAnnotations();
                for (Annotation annotation : annotationArr) {
                    if (annotation instanceof MyColumn) {
                        if (i == ((MyColumn) annotation).columnIndex()) {
                            newFields[i] = field;
                        }
                    }
                }
            }
        }

        //從第x行開始獲取
        for (int x = 1; x <= totalRowNum; x++) {
            T object = clazz.newInstance();
            //獲得第i行對象
            Row row = sheet.getRow(x);
            //如果一行里的所有單元格都為空則不放進list里面
            int rowNum = 0;
            for (int y = 0; y < cellLength; y++) {
                if (!(row == null)) {
                    Cell cell = row.getCell(y);
                    if (cell == null) {
                        rowNum++;
                    } else {
                        Field field = newFields[y];
                        String value = getCellVal(cell);
                        if (value != null && !value.equals("")) {
                            //給字段設(shè)置值.
                            setValue(field, value, object);
                        }
                    }
                }
            }
            if (rowNum != cellLength && row != null) {
                resultList.add(object);
            }
        }

        return resultList;
    }


    /**
     * 導(dǎo)出文件
     *
     * @param list
     * @param clazz
     * @param <T>
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     * @throws NoSuchMethodException
     */
    public <T> void exportFile(List<T> list, Class clazz) throws Exception {
        //1.創(chuàng)建一個工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        //2.創(chuàng)建一個工作表sheet
        HSSFSheet sheet = workbook.createSheet("test");
        //List<User> userList = userService.selectAll();
        //構(gòu)造參數(shù)依次表示起始行,截至行,起始列, 截至列
        CellRangeAddress region = new CellRangeAddress(0, 0, 0, 3);
        sheet.addMergedRegion(region);

        HSSFCellStyle style = workbook.createCellStyle();
        //水平居中
        style.setAlignment(HorizontalAlignment.CENTER);
        //垂直居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);

        HSSFRow row1 = sheet.createRow(0);
        HSSFCell cell = row1.createCell(0);
        //設(shè)置值,這里合并單元格后相當(dāng)于標(biāo)題
        cell.setCellValue("人員信息表");
        //將樣式添加生效
        cell.setCellStyle(style);

        // 獲取反射類的所有字段
        Field[] fields = clazz.getDeclaredFields();
        for (int i = 0; i < list.size(); i++) {
            //行
            HSSFRow row = sheet.createRow(i + 1);
            //對列賦值
            int colIndex2 = 0;
            for (Field field : fields) {
                String fieldName = field.getName();
                Annotation[] annotationArr = field.getDeclaredAnnotations();
                for (Annotation annotation : annotationArr) {
                    if (annotation instanceof MyColumn) {
                        if (((MyColumn) annotation).columnIndex() == colIndex2) {
                            String value = clazz.getMethod("get" + getFirstCapitalStr(fieldName)).invoke(list.get(i)).toString();
                            row.createCell(0).setCellValue(value);
                        }
                        colIndex2++;
                    }
                }
            }
        }
    }

    /**
     * 判斷字符串首字母是否為大寫,如果不是轉(zhuǎn)化為大寫
     *
     * @param str
     * @return
     */
    public static String getFirstCapitalStr(String str) {
        if (str.charAt(0) >= 'A' && str.charAt(0) <= 'Z') {
            return str;
        }
        char[] ch = str.toCharArray();
        ch[0] -= 32;
        return String.valueOf(ch);
    }

    /**
     * 給字段賦值,判斷值的類型,然后轉(zhuǎn)化成實體需要的類型值.
     *
     * @param field  字段
     * @param value  值
     * @param object 對象
     */
    private static void setValue(Field field, String value, Object object) {
        try {
            field.setAccessible(true);
            DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (field.getGenericType().toString().contains("Integer")) {
                field.set(object, Integer.valueOf(value));
            } else if (field.getGenericType().toString().contains("String")) {
                field.set(object, value);
            } else if (field.getGenericType().toString().contains("Date")) {
                field.set(object, fmt.parse(value));
            }
            field.setAccessible(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 獲取單元格中的值
     *
     * @param cell
     * @return String
     */

    private static String getCellVal(Cell cell) {
        // DecimalFormat df = new DecimalFormat("0.0000");
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String val = "";

        switch (cell.getCellTypeEnum()) {
            case STRING:
                val = cell.getRichStringCellValue().getString();
                break;
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    //日期型
                    val = fmt.format(cell.getDateCellValue());
                } else {
                    // 數(shù)字格式 todo
                    val = String.valueOf(cell.getNumericCellValue());
                }
                break;
            case BOOLEAN:
                val = String.valueOf(cell.getBooleanCellValue());
                break;
            case FORMULA:
                val = cell.getCellFormula();
                break;
            case BLANK:
                break;
            default:
                val = "";
        }

        return val;
    }


}

到此,相信大家對“如何用注釋解決反射不保證字段的順序”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI