java poi excel export 反射原理

  1. /** 
  2.  * @Title export 
  3.  * @Description 導出 
  4.  * @param mapping 
  5.  * @param form 
  6.  * @param request 
  7.  * @param response 
  8.  * @return 
  9.  * @throws Exception 
  10.  * @date Dec 11, 2012 
  11.  */  
  12. public ActionForward export(ActionMapping mapping, ActionForm form,  
  13.         HttpServletRequest request, HttpServletResponse response)  
  14.         throws Exception {  
  15.     String[] headers = new String[] { "工單ID""系統編碼""工單類型""來源""來源編號",  
  16.             "訂單編號""配送編號""配送單狀態""  訂單客戶名稱""工單狀態""客戶羣類型""創建人",  
  17.             "創建時間""提交時間""代理商名稱""代理商工號""反饋時間""完成時間""用戶要求描述",  
  18.             "物流反饋情況""客戶級別""完成時限""超時標識" };  
  19.     // 寫完後,輸出此文件  
  20.     response.setContentType("application/vnd.ms-excel");  
  21.     response.setHeader("Content-Disposition""attachment;filename="  
  22.             + URLEncoder.encode("exportFeedbackOrders""UTF8"));  
  23.     List<T> wlgdList = wlgdService.exportWlgdList(null); //記得後臺獲取結果使用泛型獲取  
  24.     // 寫入Excel  
  25.     exportToExcel("測試POI導出EXCEL文檔", headers, wlgdList, response  
  26.             .getOutputStream(), "");  
  27.     return null;  
  28. }  
  29.   
  30. /** 
  31.  *  
  32.  * @Title exportExcel 
  33.  * @Description 導出excel,利用了Java的反射原理 
  34.  * @param title 
  35.  * @param headers 
  36.  * @param dataset 
  37.  * @param out 
  38.  * @param pattern 
  39.  * @date Dec 11, 2012 
  40.  */  
  41. @SuppressWarnings( { "unchecked""deprecation" })  
  42. public void exportToExcel(String title, String[] headers,  
  43.         Collection<T> dataset, OutputStream out, String pattern) {  
  44.     // 聲明一個工作薄  
  45.     HSSFWorkbook workbook = new HSSFWorkbook();  
  46.     // 生成一個表格  
  47.     HSSFSheet sheet = workbook.createSheet(title);  
  48.     // 設置表格默認列寬度爲15個字節  
  49.     sheet.setDefaultColumnWidth((short15);  
  50.     // 生成一個樣式  
  51.     HSSFCellStyle style = workbook.createCellStyle();  
  52.     // 設置這些樣式  
  53.     style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);  
  54.     style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
  55.     style.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
  56.     style.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
  57.     style.setBorderRight(HSSFCellStyle.BORDER_THIN);  
  58.     style.setBorderTop(HSSFCellStyle.BORDER_THIN);  
  59.     style.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
  60.     // 生成一個字體  
  61.     HSSFFont font = workbook.createFont();  
  62.     font.setColor(HSSFColor.VIOLET.index);  
  63.     font.setFontHeightInPoints((short12);  
  64.     font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
  65.     // 把字體應用到當前的樣式  
  66.     style.setFont(font);  
  67.     // 生成並設置另一個樣式  
  68.     HSSFCellStyle style2 = workbook.createCellStyle();  
  69.     style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);  
  70.     style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
  71.     style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
  72.     style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
  73.     style2.setBorderRight(HSSFCellStyle.BORDER_THIN);  
  74.     style2.setBorderTop(HSSFCellStyle.BORDER_THIN);  
  75.     style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
  76.     style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
  77.     // 生成另一個字體  
  78.     HSSFFont font2 = workbook.createFont();  
  79.     font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);  
  80.     // 把字體應用到當前的樣式  
  81.     style2.setFont(font2);  
  82.   
  83.     // 聲明一個畫圖的頂級管理器  
  84.     HSSFPatriarch patriarch = sheet.createDrawingPatriarch();  
  85.     // 定義註釋的大小和位置,詳見文檔  
  86.     HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,  
  87.             000, (short42, (short65));  
  88.     // 設置註釋內容  
  89.     comment.setString(new HSSFRichTextString("可以在POI中添加註釋!"));  
  90.     // 設置註釋作者,當鼠標移動到單元格上是可以在狀態欄中看到該內容.  
  91.     comment.setAuthor("leno");  
  92.   
  93.     // 產生表格標題行  
  94.     HSSFRow row = sheet.createRow(0);  
  95.     for (short i = 0; i < headers.length; i++) {  
  96.         HSSFCell cell = row.createCell(i);  
  97.         cell.setCellStyle(style);  
  98.         HSSFRichTextString text = new HSSFRichTextString(headers[i]);  
  99.         cell.setCellValue(text);  
  100.     }  
  101.   
  102.     // 遍歷集合數據,產生數據行  
  103.     Iterator<T> it = dataset.iterator();  
  104.     int index = 0;  
  105.     while (it.hasNext()) {  
  106.         index++;  
  107.         row = sheet.createRow(index);  
  108.         Object t = it.next(); //這裏不要使用泛型強制轉換  
  109.         // 利用反射,根據javabean屬性的先後順序,動態調用getXxx()方法得到屬性值  
  110.         Field[] fields = t.getClass().getDeclaredFields();  
  111.         for (short i = 0; i < fields.length; i++) {  
  112.             HSSFCell cell = row.createCell(i);  
  113.             cell.setCellStyle(style2);  
  114.             Field field = fields[i];  
  115.             String fieldName = field.getName();  
  116.             String getMethodName = "get"  
  117.                     + fieldName.substring(01).toUpperCase()  
  118.                     + fieldName.substring(1);  
  119.             try {  
  120.                 Class tCls = t.getClass();  
  121.                 Method getMethod = tCls.getMethod(getMethodName,  
  122.                         new Class[] {});  
  123.                 Object value = getMethod.invoke(t, new Object[] {});  
  124.                 // 判斷值的類型後進行強制類型轉換  
  125.                 String textValue = "";  
  126.                 if(value == null || "".equals(value)){  
  127.                     value = "";  
  128.                 }else if (value instanceof Integer) {  
  129.                     int intValue = (Integer) value;  
  130.                     cell.setCellValue(intValue);  
  131.                 } else if (value instanceof Float) {  
  132.                     float fValue = (Float) value;  
  133.                     cell.setCellValue(fValue + "");  
  134.                 } else if (value instanceof Double) {  
  135.                     double dValue = (Double) value;  
  136.                     cell.setCellValue(dValue + "");  
  137.                 } else if (value instanceof Long) {  
  138.                     long longValue = (Long) value;  
  139.                     cell.setCellValue(longValue);  
  140.                 }  
  141.                 if (value instanceof Boolean) {  
  142.                     boolean bValue = (Boolean) value;  
  143.                     textValue = "男";  
  144.                     if (!bValue) {  
  145.                         textValue = "女";  
  146.                     }  
  147.                 } else if (value instanceof Date) {  
  148.                     Date date = (Date) value;  
  149.                     SimpleDateFormat sdf = new SimpleDateFormat(pattern);  
  150.                     textValue = sdf.format(date);  
  151.                 } else {  
  152.                     // 其它數據類型都當作字符串簡單處理  
  153.                     textValue = value.toString();  
  154.                 }  
  155.                 // 如果不是圖片數據,就利用正則表達式判斷textValue是否全部由數字組成  
  156.                 if (textValue != null) {  
  157.                     Pattern p = Pattern.compile("^//d+(//.//d+)?{1}");  
  158.                     Matcher matcher = p.matcher(textValue);  
  159.                     if (matcher.matches()) {  
  160.                         // 是數字當作double處理  
  161.                         cell.setCellValue(Double.parseDouble(textValue));  
  162.                     } else {  
  163.                         HSSFRichTextString richString = new HSSFRichTextString(  
  164.                                 textValue);  
  165.                         HSSFFont font3 = workbook.createFont();  
  166.                         font3.setColor(HSSFColor.BLUE.index);  
  167.                         richString.applyFont(font3);  
  168.                         cell.setCellValue(richString);  
  169.                     }  
  170.                 }  
  171.             } catch (SecurityException e) {  
  172.                 e.printStackTrace();  
  173.             } catch (NoSuchMethodException e) {  
  174.                 e.printStackTrace();  
  175.             } catch (IllegalArgumentException e) {  
  176.                 e.printStackTrace();  
  177.             } catch (IllegalAccessException e) {  
  178.                 e.printStackTrace();  
  179.             } catch (InvocationTargetException e) {  
  180.                 e.printStackTrace();  
  181.             } finally {  
  182.                 // 清理資源  
  183.             }  
  184.         }  
  185.     }  
  186.     try {  
  187.         workbook.write(out);  
  188.     } catch (IOException e) {  
  189.         e.printStackTrace();  
  190.     }  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章