ExcelAnnotation.java; 01 package cn.chn.chen.dev.excel; 02 03 import java.lang.annotation.ElementType; 04 import java.lang.annotation.Retention; 05 import java.lang.annotation.RetentionPolicy; 06 import java.lang.annotation.Target; 07 08 /** 09 * <p> 10 * ExcelAnnotation類主要用於-. 11 * </p> 12 * <p> 13 * 建立時間 2011-4-18 - 下午10:05:47 14 * </p> 15 * <blockquote> 16 * <h4>歷史修改記錄</h4> 17 * <ul> 18 * <li>修改人 修改時間 修改描述 19 * </ul> 20 * </blockquote> 21 * <p> 22 * copyright cd×××× 2010-2011, all rights reserved. 23 * </p> 24 * 25 * @author IT山人 26 * @since 1.0 27 * @version 1.0 28 */ 29 @Retention(RetentionPolicy.RUNTIME) 30 @Target(ElementType.FIELD) 31 public @interface ExcelAnnotation { 32 // excel導出時標題顯示的名字,若是沒有設置Annotation屬性,將不會被導出和導入 33 public String exportName(); 34 } ExcelStyle.java; 01 package cn.chn.chen.dev.excel; 02 03 import org.apache.poi.hssf.usermodel.HSSFCellStyle; 04 import org.apache.poi.hssf.usermodel.HSSFFont; 05 import org.apache.poi.hssf.usermodel.HSSFWorkbook; 06 import org.apache.poi.hssf.util.HSSFColor; 07 08 /** 09 * <p> 10 * ExcelStyle類主要用於-excel導出樣式控制. 11 * </p> 12 * <p> 13 * 建立時間 2011-4-21 - 下午12:43:11 14 * </p> 15 * @author IT山人 16 */ 17 public class ExcelStyle { 18 public static HSSFCellStyle setHeadStyle(HSSFWorkbook workbook, 19 HSSFCellStyle style) { 20 style.setFillForegroundColor(HSSFColor.SKY_BLUE.index); 21 style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); 22 style.setBorderBottom(HSSFCellStyle.BORDER_THIN); 23 style.setBorderLeft(HSSFCellStyle.BORDER_THIN); 24 style.setBorderRight(HSSFCellStyle.BORDER_THIN); 25 style.setBorderTop(HSSFCellStyle.BORDER_THIN); 26 style.setAlignment(HSSFCellStyle.ALIGN_CENTER); 27 // 生成字體 28 HSSFFont font = workbook.createFont(); 29 font.setColor(HSSFColor.VIOLET.index); 30 font.setFontHeightInPoints((short) 12); 31 font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); 32 // 把字體應用到當前的樣樣式 33 style.setFont(font); 34 return style; 35 36 } 37 38 public static HSSFCellStyle setbodyStyle(HSSFWorkbook workbook, 39 HSSFCellStyle style) { 40 style.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index); 41 style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); 42 style.setBorderBottom(HSSFCellStyle.BORDER_THIN); 43 style.setBorderLeft(HSSFCellStyle.BORDER_THIN); 44 style.setBorderRight(HSSFCellStyle.BORDER_THIN); 45 style.setBorderTop(HSSFCellStyle.BORDER_THIN); 46 style.setAlignment(HSSFCellStyle.ALIGN_CENTER); 47 style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); 48 // 生成字體 49 HSSFFont font = workbook.createFont(); 50 font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL); 51 // 把字體應用到當前的樣樣式 52 style.setFont(font); 53 return style; 54 } 55 } 1 ImportExcel.java; 001 package cn.chn.chen.dev.excel; 002 003 import java.io.File; 004 import java.io.FileInputStream; 005 import java.lang.reflect.Field; 006 import java.lang.reflect.Method; 007 import java.lang.reflect.Type; 008 import java.text.SimpleDateFormat; 009 import java.util.ArrayList; 010 import java.util.Collection; 011 import java.util.HashMap; 012 import java.util.Iterator; 013 import java.util.List; 014 import java.util.Map; 015 016 import org.apache.poi.hssf.usermodel.HSSFSheet; 017 import org.apache.poi.hssf.usermodel.HSSFWorkbook; 018 import org.apache.poi.ss.usermodel.Cell; 019 import org.apache.poi.ss.usermodel.Row; 020 021 /** 022 * <p> 023 * ImportExcel類主要用於-Excel導入(POI). 024 * </p> 025 * <p> 026 * 建立時間 2011-4-18 - 下午10:33:52 027 * </p> 028 * @author IT山人 029 */ 030 public class ImportExcel<T> { 031 032 Class<T> clazz; 033 034 public ImportExcel (Class<T> clazz) { 035 this.clazz = clazz; 036 } 037 038 public Collection<T> importExcel(File file, String...pattern) { 039 Collection<T> dist = new ArrayList<T>(); 040 try { 041 /** 042 * 類反射獲得調用方法 043 */ 044 // 獲得目標目標類的全部的字段列表 045 Field[] fields = clazz.getDeclaredFields(); 046 // 將全部標有Annotation的字段,也就是容許導入數據的字段,放入到一個map中 047 Map<String, Method> fieldMap = new HashMap<String, Method>(); 048 // 循環讀取全部字段 049 for (Field field : fields) { 050 // 獲得單個字段上的Annotation 051 ExcelAnnotation excelAnnotation = field.getAnnotation(ExcelAnnotation.class); 052 // 若是標識了Annotationd 053 if (excelAnnotation != null) { 054 String fieldName = field.getName(); 055 // 構造設置了Annotation的字段的Setter方法 056 String setMethodName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); 057 // 構造調用的method 058 Method setMethod = clazz.getMethod(setMethodName, new Class[] {field.getType()}); 059 // 將這個method以Annotaion的名字爲key來存入 060 fieldMap.put(excelAnnotation.exportName(), setMethod); 061 } 062 } 063 064 /** 065 * excel的解析開始 066 */ 067 // 將傳入的File構造爲FileInputStream; 068 FileInputStream inputStream = new FileInputStream(file); 069 // 獲得工做表 070 HSSFWorkbook book = new HSSFWorkbook(inputStream); 071 // 獲得第一頁 072 HSSFSheet sheet = book.getSheetAt(0); 073 // 獲得第一面的全部行 074 Iterator<Row> row = sheet.rowIterator(); 075 076 /** 077 * 標題解析 078 */ 079 // 獲得第一行,也就是標題行 080 Row titleRow = row.next(); 081 // 獲得第一行的全部列 082 Iterator<Cell> cellTitle = titleRow.cellIterator(); 083 // 將標題的文字內容放入到一個map中 084 Map<Integer, String> titleMap = new HashMap<Integer, String>(); 085 // 從標題第一列開始 086 int i = 0; 087 // 循環標題全部的列 088 while (cellTitle.hasNext()) { 089 Cell cell = (Cell) cellTitle.next(); 090 String value = cell.getStringCellValue(); 091 titleMap.put(i, value); 092 i++; 093 } 094 095 /** 096 * 解析內容行 097 */ 098 while (row.hasNext()) { 099 // 標題下的第一行 100 Row rown = row.next(); 101 // 行的全部列 102 Iterator<Cell> cellBody = rown.cellIterator(); 103 // 獲得傳入類的實例 104 T tObject = clazz.newInstance(); 105 // 遍歷一行的列 106 int col = 0; 107 while (cellBody.hasNext()) { 108 Cell cell = (Cell) cellBody.next(); 109 // 這裏獲得此列的對應的標題 110 String titleString = titleMap.get(col++); 111 // 若是這一列的標題和類中的某一列的Annotation相同,那麼則調用此類的的set方法,進行設值 112 if (fieldMap.containsKey(titleString)) { 113 Method setMethod = fieldMap.get(titleString); 114 //獲得setter方法的參數 115 Type[] types = setMethod.getGenericParameterTypes(); 116 //只要一個參數 117 String xclass = String.valueOf(types[0]); 118 //判斷參數類型 119 if ("class java.lang.String".equals(xclass)) { 120 setMethod.invoke(tObject, cell.getStringCellValue()); 121 } else if ("class java.util.Date".equals(xclass)) { 122 setMethod.invoke(tObject, cell.getDateCellValue()); 123 } else if ("class java.lang.Boolean".equals(xclass)) { 124 Boolean boolName = true; 125 if ("否".equals(cell.getStringCellValue())) { 126 boolName = false; 127 } 128 setMethod.invoke(tObject, boolName); 129 } else if ("class java.lang.Integer".equals(xclass)) { 130 setMethod.invoke(tObject, new Integer(String.valueOf((int)cell.getNumericCellValue()))); 131 } else if ("class java.lang.Long".equals(xclass)) { 132 setMethod.invoke(tObject, new Long(cell.getStringCellValue())); 133 } else { 134 // 135 } 136 } 137 } 138 dist.add(tObject); 139 } 140 141 } catch (Exception e) { 142 // TODO: handle exception 143 e.printStackTrace(); 144 return null; 145 } 146 return dist; 147 } 148 149 public static void main(String[] args) { 150 ImportExcel<TestVo> test = new ImportExcel<TestVo>(TestVo.class); 151 File file = new File("D:\\testOne.xls"); 152 List<TestVo> results = (List<TestVo>) test.importExcel(file); 153 SimpleDateFormat simpleDateFormat; 154 simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); 155 for (TestVo testVo : results) { 156 System.out.println(testVo.getName() + "\t" + testVo.getSex() + "\t" + simpleDateFormat.format(testVo.getBrith())); 157 } 158 } 159 } 1 ExcelExport.java; 001 package cn.chn.chen.dev.excel; 002 003 import java.io.File; 004 import java.io.FileOutputStream; 005 import java.io.IOException; 006 import java.io.OutputStream; 007 import java.lang.reflect.Field; 008 import java.lang.reflect.Method; 009 import java.text.SimpleDateFormat; 010 import java.util.ArrayList; 011 import java.util.Collection; 012 import java.util.Date; 013 import java.util.Iterator; 014 import java.util.List; 015 016 import org.apache.poi.hssf.usermodel.HSSFCell; 017 import org.apache.poi.hssf.usermodel.HSSFCellStyle; 018 import org.apache.poi.hssf.usermodel.HSSFRichTextString; 019 import org.apache.poi.hssf.usermodel.HSSFRow; 020 import org.apache.poi.hssf.usermodel.HSSFSheet; 021 import org.apache.poi.hssf.usermodel.HSSFWorkbook; 022 023 /** 024 * <p> 025 * ExcelExport類主要用於-excel導出(POI). 026 * </p> 027 * <p> 028 * 建立時間 2011-4-21 - 下午12:34:33 029 * </p> 030 * @author IT山人 031 */ 032 public class ExcelExport<T> { 033 034 //格式化日期 035 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 036 037 /** 038 * <p> 039 * exportExcel方法-poi Excel導出. 040 * </p> 041 * <p> 042 * 建立人 IT山人 建立時間 2011-4-21 - 下午09:36:21 043 * </p> 044 * @param title 工做簿名稱 045 * @param dataset 導出的數據集 046 * @param out 輸出流 047 */ 048 @SuppressWarnings("unchecked") 049 public void exportExcel(String title, Collection<T> dataset, OutputStream out) { 050 // 聲明一個工做薄 051 try { 052 //首先檢查數據看是不是正確的 053 Iterator<T> iterator = dataset.iterator(); 054 if (dataset == null || !iterator.hasNext() || title == null || out == null) { 055 throw new Exception("傳入的數據不對!"); 056 } 057 //取得實際泛型類 058 T tObject = iterator.next(); 059 Class<T> clazz = (Class<T>) tObject.getClass(); 060 061 HSSFWorkbook workbook = new HSSFWorkbook(); 062 // 生成一個表格 063 HSSFSheet sheet = workbook.createSheet(title); 064 // 設置表格默認列寬度爲20個字節 065 sheet.setDefaultColumnWidth(20); 066 // 生成一個樣式 067 HSSFCellStyle style = workbook.createCellStyle(); 068 // 設置標題樣式 069 style = ExcelStyle.setHeadStyle(workbook, style); 070 // 獲得全部字段 071 Field filed[] = tObject.getClass().getDeclaredFields(); 072 073 // 標題 074 List<String> exportfieldtile = new ArrayList<String>(); 075 // 導出的字段的get方法 076 List<Method> methodObj = new ArrayList<Method>(); 077 // 遍歷整個filed 078 for (int i = 0; i < filed.length; i++) { 079 Field field = filed[i]; 080 ExcelAnnotation excelAnnotation = field.getAnnotation(ExcelAnnotation.class); 081 // 若是設置了annottion 082 if (excelAnnotation != null) { 083 String exprot = excelAnnotation.exportName(); 084 // 添加到標題 085 exportfieldtile.add(exprot); 086 // 添加到須要導出的字段的方法 087 String fieldname = field.getName(); 088 String getMethodName = "get" + fieldname.substring(0, 1).toUpperCase() + fieldname.substring(1); 089 Method getMethod = clazz.getMethod(getMethodName, new Class[] {}); 090 methodObj.add(getMethod); 091 } 092 } 093 094 // 產生表格標題行 095 HSSFRow row = sheet.createRow(0); 096 for (int i = 0; i < exportfieldtile.size(); i++) { 097 HSSFCell cell = row.createCell(i); 098 cell.setCellStyle(style); 099 HSSFRichTextString text = new HSSFRichTextString(exportfieldtile.get(i)); 100 cell.setCellValue(text); 101 } 102 103 // 循環整個集合 104 int index = 0; 105 iterator = dataset.iterator(); 106 while (iterator.hasNext()) { 107 //從第二行開始寫,第一行是標題 108 index++; 109 row = sheet.createRow(index); 110 T t = (T) iterator.next(); 111 for (int k = 0; k < methodObj.size(); k++) { 112 HSSFCell cell = row.createCell(k); 113 Method getMethod = methodObj.get(k); 114 Object value = getMethod.invoke(t, new Object[] {}); 115 String textValue = getValue(value); 116 cell.setCellValue(textValue); 117 } 118 } 119 workbook.write(out); 120 } catch (Exception e) { 121 e.printStackTrace(); 122 } 123 } 124 125 /** 126 * <p> 127 * getValue方法-cell值處理. 128 * </p> 129 * <p> 130 * 建立人 IT山人 建立時間 2011-4-21 - 下午09:38:31 131 * </p> 132 * @param value 133 * @return 134 */ 135 public String getValue(Object value) { 136 String textValue = ""; 137 if (value == null) { 138 return textValue; 139 } 140 if (value instanceof Boolean) { 141 boolean bValue = (Boolean) value; 142 textValue = "是"; 143 if (!bValue) { 144 textValue = "否"; 145 } 146 } else if (value instanceof Date) { 147 Date date = (Date) value; 148 textValue = sdf.format(date); 149 150 } else { 151 textValue = value.toString(); 152 } 153 return textValue; 154 } 155 156 public static void main(String[] args) throws IOException { 157 OutputStream out = new FileOutputStream("D:\\testOne1.xls"); 158 ExcelExport<TestVo> ex = new ExcelExport<TestVo>(); 159 ImportExcel<TestVo> test = new ImportExcel<TestVo>(TestVo.class); 160 File file = new File("D:\\testOne.xls"); 161 List<TestVo> results = (List<TestVo>) test.importExcel(file); 162 163 ex.exportExcel("測試", results, out); 164 out.close(); 165 } 166 } 1 ImportExcell.java; 001 package cn.chn.chen.dev.excel; 002 003 import java.io.File; 004 import java.io.FileInputStream; 005 import java.io.FileNotFoundException; 006 import java.io.IOException; 007 import java.text.DecimalFormat; 008 import java.text.NumberFormat; 009 import java.util.ArrayList; 010 import java.util.HashMap; 011 import java.util.Iterator; 012 import java.util.List; 013 import java.util.Map; 014 015 import org.apache.commons.lang.StringUtils; 016 import org.apache.commons.logging.Log; 017 import org.apache.commons.logging.LogFactory; 018 import org.apache.poi.hssf.usermodel.HSSFCell; 019 import org.apache.poi.hssf.usermodel.HSSFDateUtil; 020 import org.apache.poi.hssf.usermodel.HSSFSheet; 021 import org.apache.poi.hssf.usermodel.HSSFWorkbook; 022 import org.apache.poi.ss.usermodel.Cell; 023 import org.apache.poi.ss.usermodel.Row; 024 025 /** 026 * <p> 027 * ImportExcell類主要用於-. 028 * </p> 029 * <p> 030 * 建立時間 2011-4-21 - 下午04:45:33 031 * </p> 032 * @author IT山人 033 */ 034 public class ImportExcell { 035 private static final Log log = LogFactory.getLog(ImportExcell.class); 036 /** 037 * <p> 038 * readExcel方法-讀取excel,行爲list,列爲Map. 039 * </p> 040 * <p> 041 * 建立人 IT山人 建立時間 2011-4-21 - 下午09:46:33 042 * </p> 043 * @param file excel文件 044 * @return excel表數據集合-行爲list,列爲Map 045 */ 046 public List<Map<String, String>> readExcel(File file) { 047 log.info("讀取excel開始..."); 048 List<Map<String, String>> dataset = new ArrayList<Map<String, String>>(); 049 050 try { 051 // 將傳入的File構造爲FileInputStream; 052 FileInputStream inputStream = new FileInputStream(file); 053 // 獲得工做表 054 HSSFWorkbook book = new HSSFWorkbook(inputStream); 055 // 獲得第一頁 056 HSSFSheet sheet = book.getSheetAt(0); 057 // 獲得第一面的全部行 058 Iterator<Row> rowIterator = sheet.rowIterator(); 059 060 // 獲得第一行,也就是標題行 061 @SuppressWarnings("unused") 062 Row titleRow = rowIterator.next(); 063 064 while (rowIterator.hasNext()) { 065 Row row = rowIterator.next(); 066 Map<String, String> map = this.creatObjectByRow(row); 067 dataset.add(map); 068 } 069 } catch (FileNotFoundException e1) { 070 // TODO Auto-generated catch block 071 e1.printStackTrace(); 072 } catch (IOException e2) { 073 // TODO Auto-generated catch block 074 e2.printStackTrace(); 075 } catch (Exception e) { 076 // TODO: handle exception 077 } 078 log.info("讀取excel結束..."); 079 return dataset; 080 } 081 082 /** 083 * <p> 084 * creatObjectByRow方法-將每行的數據裝載Map中. 085 * </p> 086 * <p> 087 * 建立人 IT山人 建立時間 2011-4-21 - 下午09:48:17 088 * </p> 089 * @param row 090 * @return 091 */ 092 private Map<String, String> creatObjectByRow(Row row) { 093 // 行的全部列 094 Iterator<Cell> cellBody = row.cellIterator(); 095 // 遍歷一行的列 096 int col = 1; 097 Map<String, String> map = new HashMap<String, String>(); 098 while (cellBody.hasNext()) { 099 String field = String.valueOf(col++); 100 Cell cell = cellBody.next(); 101 if (cell != null) { 102 switch (cell.getCellType()) { 103 case HSSFCell.CELL_TYPE_STRING: // 字符 104 map.put(field, StringUtils.trim(cell.getStringCellValue())); 105 break; 106 case HSSFCell.CELL_TYPE_BOOLEAN: // 布爾 107 map.put(field, StringUtils.trim(cell.getStringCellValue())); 108 break; 109 case HSSFCell.CELL_TYPE_NUMERIC: // 數字 110 if (HSSFDateUtil.isCellDateFormatted(cell)) {// 是否爲日期格式 111 map.put(field, String.valueOf(cell.getDateCellValue())); 112 } else { 113 Double cellValue_dob = cell.getNumericCellValue();// 讀取cell內數據 114 if (String.valueOf(cellValue_dob).length() > 11) { // 若是讀取到的是手機號碼,須要匹配數字格式 115 DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(); 116 //format.applyPattern("00000000000"); 117 map.put(field, format.format(cellValue_dob)); 118 } else { // 若是讀取到的是比較短的數字,則去掉尾數(.0)後顯示 119 map.put(field, cellValue_dob.toString().substring(0, cellValue_dob.toString().length() - 2)); 120 } 121 } 122 break; 123 case HSSFCell.CELL_TYPE_FORMULA: // 公式 124 map.put(field, String.valueOf(cell.getNumericCellValue())); 125 break; 126 case HSSFCell.CELL_TYPE_BLANK: // 空 127 map.put(field, StringUtils.trim(cell.getStringCellValue())); 128 break; 129 case HSSFCell.CELL_TYPE_ERROR: // 異常 130 map.put(field, StringUtils.trim(cell.getStringCellValue())); 131 break; 132 default: 133 map.put(field, StringUtils.trim(cell.getStringCellValue())); 134 break; 135 } 136 } 137 } 138 return map; 139 } 140 141 public static void main(String[] args) { 142 // TODO Auto-generated method stub 143 ImportExcell inport = new ImportExcell(); 144 File file = new File("D:\\testOne.xls"); 145 List<Map<String, String>> mapList = inport.readExcel(file); 146 for (Map<String, String> map : mapList) { 147 // Iterator<Entry<String, String>> iterator = map.entrySet().iterator(); 148 // while (iterator.hasNext()) { 149 // Map.Entry<String, String> entry = iterator.next(); 150 // String key = entry.getKey(); 151 // String value = entry.getValue(); 152 // System.out.println("key:" + key + "\tvalue:" + value); 153 // } 154 TestVo t = new TestVo(); 155 t.setName(map.get("1")); 156 System.out.println(t.getName()); 157 } 158 } 159 } 1 TestVo.java; 01 public class TestVo { 02 03 @ExcelAnnotation(exportName="姓名") 04 private String name; 05 06 @ExcelAnnotation(exportName="性別") 07 private Integer sex; 08 09 @ExcelAnnotation(exportName="出生年月") 10 private Date brith; 11 12 /** 13 * @return 返回 name 14 */ 15 public String getName() { 16 return name; 17 } 18 19 /** 20 * @param name 設置 name 21 */ 22 public void setName(String name) { 23 this.name = name; 24 } 25 26 /** 27 * @return 返回 sex 28 */ 29 public Integer getSex() { 30 return sex; 31 } 32 33 /** 34 * @param sex 設置 sex 35 */ 36 public void setSex(Integer sex) { 37 this.sex = sex; 38 } 39 40 /** 41 * @return 返回 brith 42 */ 43 public Date getBrith() { 44 return brith; 45 } 46 47 /** 48 * @param brith 設置 brith 49 */ 50 public void setBrith(Date brith) { 51 this.brith = brith; 52 } 53 54 }