package util; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFDateUtil; 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.poifs.filesystem.POIFSFileSystem; import demo.domain.User; public class ExcelBase { /*** * public List getExcelData(String fileName,Class clazz) throws Exception { * List list = readExcel(clazz, fileName,0); return list; } */ public List[] getExcelData(String fileName, Class... clazzs) throws Exception { List[] lists = null; if (clazzs != null) { lists = new List[clazzs.length]; for (int i = 0; i < lists.length; i++) { lists[i] = readExcel(clazzs[i], fileName, 0); } } return lists; } /*** * public Map<String, List> getExcelData(Class[] clazzs, String fileName) * throws Exception { Map<String, List> map = new HashMap<String, List>(); * for(int i = 0;i < clazzs.length;i++){ List list = readExcel(clazzs[i], * fileName,i); map.put(clazzs[i].getName(), list); } return map; } */ public List readExcel(Class clazz, String fileName, int sheetIndex) throws Exception { BufferedInputStream bis = new BufferedInputStream(new FileInputStream( new File(fileName))); // 打開HSSFWorkbook POIFSFileSystem fs = new POIFSFileSystem(bis); HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet sheet = wb.getSheetAt(sheetIndex); List list = new ArrayList(); // 獲取標題 HSSFRow titelRow = sheet.getRow(0); Map<Integer, String> titel = new HashMap<Integer, String>(); for (int columnIndex = 0; columnIndex < titelRow.getLastCellNum(); columnIndex++) { HSSFCell cell = titelRow.getCell(columnIndex); if (cell != null) { String value = cell.getStringCellValue(); titel.put(Integer.valueOf(columnIndex), value); } } // 獲取值 for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) { HSSFRow row = sheet.getRow(rowIndex); Object obj = clazz.newInstance(); for (int columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex++) { HSSFCell cell = row.getCell(columnIndex); if (cell != null) { /** * Object value = null; // 值 Class[] fType = { String.class * }; // 注意:必定要設成這個,不然可能會出現亂碼 // * cell.setEncoding(HSSFCell.ENCODING_UTF_16); * System.out.println(cell.getCellType()); switch * (cell.getCellType()) { case HSSFCell.CELL_TYPE_STRING: * value = cell.getStringCellValue(); break; case * HSSFCell.CELL_TYPE_NUMERIC: if * (HSSFDateUtil.isCellDateFormatted(cell)) { value = * cell.getDateCellValue(); fType[0] = Date.class; } else { * value = Integer.valueOf((int)cell.getNumericCellValue()); * fType[0] = Integer.class; } break; case * HSSFCell.CELL_TYPE_FORMULA: // 導入時若是爲公式生成的數據則無值 if * (!cell.getStringCellValue().equals("")) { value = * cell.getStringCellValue(); } else { value = * cell.getNumericCellValue(); } break; case * HSSFCell.CELL_TYPE_BLANK: break; case * HSSFCell.CELL_TYPE_ERROR: value = null; break; case * HSSFCell.CELL_TYPE_BOOLEAN: value = * (cell.getBooleanCellValue() == true ? "Y" : "N"); break; * default: value = ""; } */ // 最初想法 // 注意:必定要設成這個,不然可能會出現亂碼 // cell.setEncoding(HSSFCell.ENCODING_UTF_16); String value = null; switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_STRING: value = cell.getStringCellValue(); break; case HSSFCell.CELL_TYPE_NUMERIC: if (HSSFDateUtil.isCellDateFormatted(cell)) { Date date = cell.getDateCellValue(); if (date != null) { value = new SimpleDateFormat("yyyy-MM-dd") .format(date); } else { value = ""; } } else { value = new DecimalFormat("0").format(cell .getNumericCellValue()); } break; case HSSFCell.CELL_TYPE_FORMULA: // 導入時若是爲公式生成的數據則無值 if (!cell.getStringCellValue().equals("")) { value = cell.getStringCellValue(); } else { value = cell.getNumericCellValue() + ""; } break; case HSSFCell.CELL_TYPE_BLANK: break; case HSSFCell.CELL_TYPE_ERROR: value = ""; break; case HSSFCell.CELL_TYPE_BOOLEAN: value = (cell.getBooleanCellValue() == true ? "Y" : "N"); break; default: value = ""; } Method method = clazz.getMethod("set" + toUpperFirstCase(titel.get(Integer .valueOf(columnIndex))), String.class); method.invoke(obj, value); } } list.add(obj); } return list; } /** * @author popl @ 首字母大寫 */ public String toUpperFirstCase(String str) { return str.replaceFirst(str.substring(0, 1), str.substring(0, 1) .toUpperCase()); } /** * 寫文件 * * @throws Exception */ public void createExcelFile(String fileName, List... lists) throws Exception { // 第一步,建立一個webbook,對應一個Excel文件 HSSFWorkbook wb = new HSSFWorkbook(); // 第二步,在webbook中添加一個sheet,對應Excel文件中的sheet if (lists != null) { Class clazz = lists[0].get(0).getClass(); Field[] fields = clazz.getDeclaredFields(); HSSFSheet sheet = wb.createSheet(clazz.getCanonicalName()); // 第三步,在sheet中添加表頭第0行 HSSFRow rowTitle = sheet.createRow(0); // 第四步,建立單元格,並設置值表頭 設置表頭居中 HSSFCellStyle style = wb.createCellStyle(); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 建立一個居中格式 for (int clolumnIndex = 0; clolumnIndex < fields.length; clolumnIndex++) { HSSFCell cell = rowTitle.createCell(clolumnIndex); cell.setCellValue(fields[clolumnIndex].getName()); cell.setCellStyle(style); } for (List list : lists) { // 數據 Method[] mds = getGetMethod(clazz); for (int rowIndex = 0; rowIndex < list.size(); rowIndex++) { HSSFRow row = sheet.createRow(rowIndex + 1); for (int clolumnIndex = 0; clolumnIndex < fields.length; clolumnIndex++) { HSSFCell cell = row.createCell(clolumnIndex); Object obj = mds[clolumnIndex].invoke(list .get(rowIndex)); if (obj != null) { if(obj instanceof Date){ // obj = new SimpleDateFormat("yyyy-MM-dd").format((Date)obj); cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format((Date)obj)); } else if(obj instanceof Integer || obj instanceof Double || obj instanceof Float || obj instanceof Long){ cell.setCellValue(Double.parseDouble(obj.toString())); }else if(obj instanceof Boolean ){ cell.setCellValue((Boolean)obj); }else{ cell.setCellValue(obj.toString()); } cell.setCellStyle(style); } } } } FileOutputStream fout = new FileOutputStream(fileName); wb.write(fout); fout.close(); } } public Method[] getGetMethod(Class clazz) throws Exception { Field[] fields = clazz.getDeclaredFields(); Method[] methods = new Method[fields.clone().length]; for (int i = 0; i < fields.length; i++) { PropertyDescriptor pd = new PropertyDescriptor(fields[i].getName(), clazz); methods[i] = pd.getReadMethod(); } return methods; } public static void main(String[] arg) throws Exception { List[] lists = new ExcelBase().getExcelData("D:/temp/123.xls", User.class); for (List list : lists) { for (int i = 0; i < list.size(); i++) { User user = (User) list.get(i); System.out.println(user.getId() + "\t" + user.getName() + "\t" + user.getBirthday() + "\t" + user.getAge() + "\t" + user.getSex() + "\t" + user.getEmail() + "\t"); } } new ExcelBase().createExcelFile("E:/test/user.xls", lists); } }
新手寫代碼,求大神指點,我認爲應該有不少不足,但願幫我指出java
找到一個能夠彌補一點不足之處的方法了web
在得到屬性名稱的時候把他反射成Field,得到Field的type再經過逐一判斷,這樣可以實現基本類型的的set了
數據庫
public List readExcel(Class clazz, String fileName, int sheetIndex) throws Exception { BufferedInputStream bis = new BufferedInputStream(new FileInputStream( new File(fileName))); // 打開HSSFWorkbook POIFSFileSystem fs = new POIFSFileSystem(bis); HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet sheet = wb.getSheetAt(sheetIndex); List list = new ArrayList(); // 獲取標題 HSSFRow titelRow = sheet.getRow(0); Map<Integer, String> titel = new HashMap<Integer, String>(); for (int columnIndex = 0; columnIndex < titelRow.getLastCellNum(); columnIndex++) { HSSFCell cell = titelRow.getCell(columnIndex); if (cell != null) { String value = cell.getStringCellValue(); titel.put(Integer.valueOf(columnIndex), value); } } // 獲取值 for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) { HSSFRow row = sheet.getRow(rowIndex); Object obj = clazz.newInstance(); for (int columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex++) { HSSFCell cell = row.getCell(columnIndex); if (cell != null) { String value = null; switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_STRING: value = cell.getStringCellValue(); break; case HSSFCell.CELL_TYPE_NUMERIC: if (HSSFDateUtil.isCellDateFormatted(cell)) { Date date = cell.getDateCellValue(); if (date != null) { value = new SimpleDateFormat("yyyy-MM-dd") .format(date); } else { value = ""; } } else { value = new DecimalFormat("0").format(cell .getNumericCellValue()); } break; case HSSFCell.CELL_TYPE_FORMULA: // 導入時若是爲公式生成的數據則無值 if (!cell.getStringCellValue().equals("")) { value = cell.getStringCellValue(); } else { value = cell.getNumericCellValue() + ""; } break; case HSSFCell.CELL_TYPE_BLANK: break; case HSSFCell.CELL_TYPE_ERROR: value = ""; break; case HSSFCell.CELL_TYPE_BOOLEAN: value = (cell.getBooleanCellValue() == true ? "Y" : "N"); break; default: value = ""; } Field field = clazz.getDeclaredField(titel.get(Integer.valueOf(columnIndex))); Class fieldType = field.getType(); Object agge = null; if(fieldType.isAssignableFrom(Integer.class)){ agge = Integer.valueOf(value); }else if(fieldType.isAssignableFrom(Double.class)){ agge = Double.valueOf(value); }else if(fieldType.isAssignableFrom(Float.class)){ agge = Float.valueOf(value); }else if(fieldType.isAssignableFrom(Long.class)){ agge = Long.valueOf(value); }else if(fieldType.isAssignableFrom(Date.class)){ agge = new SimpleDateFormat("yyyy-MM-dd").parse(value); }else if(fieldType.isAssignableFrom(Boolean.class)){ agge = "Y".equals(value) || "1".equals(value); }else if(fieldType.isAssignableFrom(String.class)){ agge = value; } //我的感受char跟byte就不用判斷了 用這兩個類型的不多若是是從數據庫用IDE生成的話就不會出現了 Method method = clazz.getMethod("set" + toUpperFirstCase(titel.get(Integer .valueOf(columnIndex))), fieldType); method.invoke(obj, agge); } } list.add(obj); } return list; }
其實toUpperFirstCase方法應經能夠去掉了 跟讀的那種方法同樣用屬性的write方法apache
不知道該的有什麼卻陷沒,求幫忙指點下dom