本篇內(nèi)容主要講解“如何用注釋解決反射不保證字段的順序”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學(xué)習(xí)“如何用注釋解決反射不保證字段的順序”吧!
創(chuàng)新互聯(lián)主打移動網(wǎng)站、成都網(wǎng)站建設(shè)、成都網(wǎng)站設(shè)計、網(wǎng)站改版、網(wǎng)絡(luò)推廣、網(wǎng)站維護、主機域名、等互聯(lián)網(wǎng)信息服務(wù),為各行業(yè)提供服務(wù)。在技術(shù)實力的保障下,我們?yōu)榭蛻舫兄Z穩(wěn)定,放心的服務(wù),根據(jù)網(wǎng)站的內(nèi)容與功能再決定采用什么樣的設(shè)計。最后,要實現(xiàn)符合網(wǎng)站需求的內(nèi)容、功能與設(shè)計,我們還會規(guī)劃穩(wěn)定安全的技術(shù)方案做保障。
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* @return * @throws Exception */ public List getListFromFile(MultipartFile file, Class clazz) throws Exception { //最終返回數(shù)據(jù) List resultList = new ArrayList (); 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 * @throws InvocationTargetException * @throws IllegalAccessException * @throws NoSuchMethodException */ public void exportFile(List list, Class clazz) throws Exception { //1.創(chuàng)建一個工作簿 HSSFWorkbook workbook = new HSSFWorkbook(); //2.創(chuàng)建一個工作表sheet HSSFSheet sheet = workbook.createSheet("test"); //List 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; } }
到此,相信大家對“如何用注釋解決反射不保證字段的順序”有了更深的了解,不妨來實際操作一番吧!這里是創(chuàng)新互聯(lián)網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!