您好,登錄后才能下訂單哦!
本篇內容主要講解“如何用注釋解決反射不保證字段的順序”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“如何用注釋解決反射不保證字段的順序”吧!
Talk is cheap, show me the code.直接上碼!
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface MyColumn { int columnIndex() default 0; }
public class PoiUtil { /** * 獲取文件內容列表 * * @param file * @param clazz * @param <T> * @return * @throws Exception */ public <T> List<T> getListFromFile(MultipartFile file, Class<T> clazz) throws Exception { //最終返回數據 List<T> resultList = new ArrayList<T>(); InputStream is = file.getInputStream(); //使用工廠方法創建. Workbook wb = WorkbookFactory.create(is); Sheet sheet = wb.getSheetAt(0); int totalRowNum = sheet.getLastRowNum(); //獲得總列數 int cellLength = sheet.getRow(0).getPhysicalNumberOfCells(); //獲取反射類的所有字段 Field[] fields = clazz.getDeclaredFields(); //創建一個字段數組,用于和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("")) { //給字段設置值. setValue(field, value, object); } } } } if (rowNum != cellLength && row != null) { resultList.add(object); } } return resultList; } /** * 導出文件 * * @param list * @param clazz * @param <T> * @throws InvocationTargetException * @throws IllegalAccessException * @throws NoSuchMethodException */ public <T> void exportFile(List<T> list, Class clazz) throws Exception { //1.創建一個工作簿 HSSFWorkbook workbook = new HSSFWorkbook(); //2.創建一個工作表sheet HSSFSheet sheet = workbook.createSheet("test"); //List<User> userList = userService.selectAll(); //構造參數依次表示起始行,截至行,起始列, 截至列 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); //設置值,這里合并單元格后相當于標題 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++; } } } } } /** * 判斷字符串首字母是否為大寫,如果不是轉化為大寫 * * @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); } /** * 給字段賦值,判斷值的類型,然后轉化成實體需要的類型值. * * @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 { // 數字格式 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; } }
到此,相信大家對“如何用注釋解決反射不保證字段的順序”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。