2019獨角獸企業重金招聘Python工程師標準>>>
反射 導出的數組轉變成對象
private static Object expexcelMaptobean(Class<?> cobj,Map<String,String> map,int[] expColums,String[] params) throws InstantiationException, IllegalAccessException{Object t=cobj.newInstance();Set<Entry<String, String>> set=map.entrySet();int i=0;for(Entry<String, String> s:set){String field=s.getKey();field=field.substring(0,1).toUpperCase()+field.substring(1);try {Method m = null ;for(Class<?> clazz = cobj; clazz != Object.class ; clazz = clazz.getSuperclass()) {Method[] mehhods= clazz.getDeclaredMethods();for(Method md:mehhods){if(("set"+field).equals(md.getName())){Type[] paramclass=md.getParameterTypes();for(Type paramType:paramclass){String paramval=params[expColums[i]]+"";m =clazz.getDeclaredMethod("set"+field,(Class[])paramclass) ;if(paramType.getTypeName().equals("java.math.BigDecimal") ){boolean isNum = paramval.matches("\\d+(\\.\\d+)?");if(!isNum){m.invoke(t,new BigDecimal(0));}else{m.invoke(t,new BigDecimal(paramval));}}else{m.invoke(t,paramval);}}}}}} catch (Exception e) {e.printStackTrace();}if(expColums[i]>params.length-1){break;}if(i==expColums.length-1 && (params.length>=expColums.length)){break;}i++;}return t;}
測試
public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {String[] params={"100","10000","ccc","dddd","eeee"};int[] expColums={1,2};Map<String,String> titleMap = new LinkedHashMap<String,String>();titleMap.put("ackAmt", "產品代碼"); titleMap.put("appno", "產品代碼"); Bean f=(Bean )expexcelMaptobean(Bean.class,titleMap,expColums,params);System.out.println(f.getAckAmt());}
導出excel 工具類
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;public final class ExportExcel {public static String saveExpExcelDir; //導出excel保存位置private ExportExcel() {}static{Map<String,String> map = System.getenv();saveExpExcelDir="C:\\Users"+File.separator+map.get("USERNAME")+File.separator+"Desktop"+File.separator+"ccjj";}/**** 工作簿*/private static HSSFWorkbook workbook;/**** sheet*/private static HSSFSheet sheet;/**** 標題行開始位置*/private static final int TITLE_START_POSITION = 0;/**** 時間行開始位置*/private static final int DATEHEAD_START_POSITION = 0;/**** 表頭行開始位置*/private static final int HEAD_START_POSITION = 0;/**** 文本行開始位置*/private static final int CONTENT_START_POSITION = 1;/*** * @param dataList* 對象集合* @param titleMap* 表頭信息(對象屬性名稱->要顯示的標題值)[按順序添加]* @param sheetName* sheet名稱和表頭值*/public static void excelExport(List<?> dataList, Map<String, String> titleMap, String sheetName,String filepathandname) {initHSSFWorkbook(sheetName);// 初始化workbook// createTitleRow(titleMap, sheetName);// 標題行// createDateHeadRow(titleMap);// 時間行createHeadRow(titleMap);// 表頭行createContentRow(dataList, titleMap);// 文本行// autoSizeColumn(100);//設置自動伸縮try {OutputStream out = new FileOutputStream(filepathandname);workbook.write(out);out.close();}catch (Exception e) {e.printStackTrace();}}/**** * @param sheetName* sheetName*/private static void initHSSFWorkbook(String sheetName) {workbook = new HSSFWorkbook();sheet = workbook.createSheet(sheetName);}/*** 生成標題(第零行創建)* @param titleMap 對象屬性名稱->表頭顯示名稱* @param sheetName sheet名稱*/private static void createTitleRow(Map<String, String> titleMap, String sheetName) {CellRangeAddress titleRange = new CellRangeAddress(0, 0, 0, titleMap.size() - 1);sheet.addMergedRegion(titleRange);HSSFRow titleRow = sheet.createRow(TITLE_START_POSITION);HSSFCell titleCell = titleRow.createCell(0);titleCell.setCellValue(sheetName);}/*** 創建時間行(第一行創建)* @param titleMap 對象屬性名稱->表頭顯示名稱*/private static void createDateHeadRow(Map<String, String> titleMap) {CellRangeAddress dateRange = new CellRangeAddress(1, 1, 0, titleMap.size() - 1);sheet.addMergedRegion(dateRange);HSSFRow dateRow = sheet.createRow(DATEHEAD_START_POSITION);HSSFCell dateCell = dateRow.createCell(0); dateCell.setCellValue(new SimpleDateFormat("yyyy年MM月dd日").format(new Date()));}/*** 創建表頭行(第二行創建)* @param titleMap 對象屬性名稱->表頭顯示名稱*/private static void createHeadRow(Map<String, String> titleMap) {// 第1行創建HSSFRow headRow = sheet.createRow(HEAD_START_POSITION);int i = 0;for (String entry : titleMap.keySet()) {HSSFCell headCell = headRow.createCell(i);headCell.setCellValue(titleMap.get(entry));i++;}}/*** * @param dataList 對象數據集合* @param titleMap 表頭信息*/private static void createContentRow(List<?> dataList, Map<String, String> titleMap) {try {int i=0;for (Object obj : dataList) {HSSFRow textRow = sheet.createRow(CONTENT_START_POSITION + i);int j = 0;for (String entry : titleMap.keySet()) {String method = "get" + entry.substring(0, 1).toUpperCase() + entry.substring(1);Method m = null ;for(Class<?> clazz = obj.getClass(); clazz != Object.class ; clazz = clazz.getSuperclass()) {try { m = clazz.getDeclaredMethod(method, null) ; } catch (Exception e) { }}String value = m.invoke(obj, null).toString();HSSFCell textcell = textRow.createCell(j);sheet.setColumnWidth(j, letterCount(value,750,250));textcell.setCellValue(value);j++;}i++;}}catch (Exception e) {}}/*** 自動伸縮列(如非必要,請勿打開此方法,耗內存)* @param size 列數*/private static void autoSizeColumn(Integer size) { for (int j = 0; j < size; j++) {// sheet.autoSizeColumn(j);sheet.setColumnWidth(j, 256*size+184);}}/**創建文件夾**/public static String createDir(String destDirName){File dir = new File(destDirName); // if (!dir.exists()) { if (!destDirName.endsWith(File.separator)) { destDirName = destDirName + File.separator; }dir.mkdirs();// }return destDirName; }/**計算內容含有字體個數**/private static int letterCount(String message,int chinese_len,int other_len){if(message ==null){return 1;}Pattern p = Pattern.compile("[\u4E00-\u9FA5]+"); Matcher m = p.matcher(message); int zm=0;int num=0;int chinese=0;int other=0;char [] ch = message.toCharArray();for(int i=0;i<ch.length;i++){if((ch[i]>='a' && ch[i]<='z') || (ch[i]>='A' && ch[i]<='Z')){zm=zm+1;}else if(ch[i]>47 && ch[i]<58){num=num+1;}if(m.find()){chinese=chinese+m.group(0).length()+1;}else{other=other+1;other=(other-chinese)<=0?1:(other-chinese);}}int totalcount=(chinese*chinese_len)+(zm+num+(other))*other_len;return totalcount;}}