先說說優化前,怎么做EXCEL導出功能的:
1. 先定義一個VO類,類中的字段按照EXCEL的順序定義,並且該類只能用於EXCEL導出使用,不能隨便修改。
2. 將查詢到的結果集循環寫入到這個VO類中。
3. 將這個VO類的數據集寫入到EXCEL中。
缺點:
1.每次做一個功能的excel導出需要定義一個vo類,並且vo類不可隨便變更。
2. 從數據庫查詢到結果集不能直接輸出到excel,需要二次遍歷寫入到vo中。
3. excel導出的順序必須與vo定義的字段順序一致,並且輸出vo中所有的字段。
針對以上情況做了一次改進:
1. 去掉每次導出都必須定義vo類
2. 直接從數據庫獲取數據集來寫入到excel中
3. 可以自己指定要導出的字段
如何實現呢:
1. 查詢要使用的結果集,比如產品的列表信息放到list中。
List<TProduct> list = productService.getProductExpiredList(vo);
2.定一個2個字符串,分別為字段和字段名,這兩個來自於查詢的結果集的對象中。如下
String colName = "RR商品編碼,規格型號,商品名稱,單位,產品類別,批准文號,有效期,備注";
String columnFieldStr = "ptCode,ptRuleModel,ptName,um.umUm1,proType.typeName,ptPemissionNO,ptExpiryDate,ptRemark";
3. 調用自定義的工具類
ExcelUtil excel = new ExcelUtil(); excel.exportExcelNew("商品許可到期報表", colName, columnFieldStr, list, response);
這個ExcelUtil是自己封裝的一個工具類,重點來了,我們定義的字段的名,可以通過反射的原理來獲取對象中的值。
所以下面重點介紹下怎么解析columnFieldStr來獲取值。
//拿到字段的字符串,先轉為數組 String[] columnFields = columnFieldStr.split(","); //中間省略部分代碼 ... ...
//迭代器來獲取list中的對象,由於ExcelUtil是一個工具類,所以不指定具體的對象,使用泛型T表示,更具有通用性 Iterator<T> it = list.iterator();
while (it.hasNext()) {
T t = (T) it.next(); //獲取list中對象
//遍歷指定的字段數組 for (short i = 0; i < columnFields.length; i++) { String fieldName = columnFields[i]; //獲取字段名 //使用自定義的getValue方法獲取值 //這個getValue其實是一個遞歸方法,
//參數t為對象,fieldName為我們寫的要輸出的字段 Object value = getValue(t,fieldName); //拿到value值后寫入到excel中,這里省略部分代碼....
} //for
} //while
重點中的重點:getValue方法的解析
對於一般的類中的標准類型,可以直接通過Field反射來獲取值,但是注意到我們的指定的字段中有um.umUml和proType.typeName這個兩個字段。
um和proType屬於對象T中的一個屬性,本身也是一個類對象,所以我們需要使用遞歸方法來獲取對象屬性中的類的對象的值, 有點繞口。
所以下面代碼中加了(.)點號判斷,如果指定的字段帶有點號,需要做進一步的解析來獲取值。這個有點類似於springmvc中的包裝對象的參數綁定。
如例子中的對象TProduct中的部分屬性如下,所以我們要獲取單位的名稱,定義字段時則為um.umUm1,后面的umUm1為類Um中的屬性。
@Entity @Table(name="T_PRODUCT") public class TProduct extends BaseDomain { /** * 單位 * null */ @Column(name="UM_ID") private String umId; @ManyToOne @JoinColumn(name="UM_ID",insertable=false,updatable=false) private TUm um; /** * 類別 * null */ @Column(name="PT_TYPE") private String ptType; @ManyToOne @JoinColumn(name="PT_TYPE",insertable=false,updatable=false) private TProType proType; //省略部分代碼......
getValue完整方法如下:
//遞歸調用,獲取多層包裝類中的值 private Object getValue(Object obj,String colField) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, ClassNotFoundException { Object value = null; if(colField.indexOf(".") > 0){ String fieldName = colField.substring(0,colField.indexOf(".")); Field field = obj.getClass().getDeclaredField(fieldName); Class<?> clazz = Class.forName(field.getType().getName()); field.setAccessible(true); Object fieldObj = field.get(obj); String nextField = colField.substring(colField.indexOf(".")+1); value = getValue(fieldObj,nextField); } else { Field field = obj.getClass().getDeclaredField(colField); field.setAccessible(true); value = field.get(obj); } return value; }
最后放上完整的ExcelUtil工具類代碼供參考:
public class ExcelUtil<T> { /** * 新的EXCEL輸出工具類 * * @param fileName * @param columnNameStr * 指定輸出的字段名,逗號分開 * @param columnFieldStr * 指定輸出的字段,逗號分開 * @param dataList * @param response * @throws IOException * @throws ClassNotFoundException * @throws NoSuchFieldException */ public void exportExcelNew(String fileName, String columnNameStr,String columnFieldStr, List<T> dataList,HttpServletResponse response) throws Exception { String[] columnNames = URLDecoder.decode(columnNameStr, "UTF-8").split(","); String[] columnFields = columnFieldStr.split(","); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss"); String pattern = sdf.format(new Date()); // 聲明一個工作薄 HSSFWorkbook workbook = new HSSFWorkbook(); // 生成一個表格 HSSFSheet sheet = workbook.createSheet(fileName + pattern); // 設置表格默認列寬度為15個字節 sheet.setDefaultColumnWidth((short) 15); // 生成一個樣式 HSSFCellStyle style = workbook.createCellStyle(); // 設置這些樣式 // style.setFillForegroundColor(HSSFColor.SKY_BLUE.index); //設置前景色 // style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); style.setBorderBottom(HSSFCellStyle.BORDER_THIN); style.setBorderLeft(HSSFCellStyle.BORDER_THIN); style.setBorderRight(HSSFCellStyle.BORDER_THIN); style.setBorderTop(HSSFCellStyle.BORDER_THIN); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 生成一個字體 HSSFFont font = workbook.createFont(); // font.setColor(HSSFColor.VIOLET.index); font.setFontHeightInPoints((short) 10); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 把字體應用到當前的樣式 style.setFont(font); // 生成並設置另一個樣式 HSSFCellStyle style2 = workbook.createCellStyle(); // style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index); //生成前景色 // style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); style2.setBorderBottom(HSSFCellStyle.BORDER_THIN); style2.setBorderLeft(HSSFCellStyle.BORDER_THIN); style2.setBorderRight(HSSFCellStyle.BORDER_THIN); style2.setBorderTop(HSSFCellStyle.BORDER_THIN); style2.setAlignment(HSSFCellStyle.ALIGN_LEFT); style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 生成另一個字體 HSSFFont font2 = workbook.createFont(); font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL); font2.setFontName("宋體"); // 設置字體 font2.setFontHeightInPoints((short) 10); // 設置字體大小 // 把字體應用到當前的樣式 style2.setFont(font2); // 聲明一個畫圖的頂級管理器 HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); // 定義注釋的大小和位置,詳見文檔 // HSSFComment comment = patriarch.createComment(new // HSSFClientAnchor(0,0, 0, 0, (short) 4, 2, (short) 6, 5)); // 設置注釋內容 // comment.setString(new HSSFRichTextString("可以在POI中添加注釋!")); // 設置注釋作者,當鼠標移動到單元格上是可以在狀態欄中看到該內容. // comment.setAuthor("leno"); // 產生表格標題行 HSSFRow row = sheet.createRow(0); for (short i = 0; i < columnNames.length; i++) { HSSFCell cell = row.createCell(i); cell.setCellStyle(style); HSSFRichTextString text = new HSSFRichTextString(columnNames[i]); cell.setCellValue(text); } // 遍歷集合數據,產生數據行 Iterator<T> it = dataList.iterator(); int index = 0; // HSSFFont font3 = workbook.createFont(); while (it.hasNext()) { index++; row = sheet.createRow(index); T t = (T) it.next(); for (short i = 0; i < columnFields.length; i++) { HSSFCell cell = row.createCell(i); cell.setCellStyle(style2); String fieldName = columnFields[i]; try { Object value = getValue(t, fieldName); // 判斷值的類型后進行強制類型轉換 String textValue = null; if (value instanceof String) { textValue = value.toString(); } else if (value instanceof Integer) { textValue = value.toString(); } else if (value instanceof BigInteger) { textValue = value.toString(); } else if (value instanceof Float) { textValue = value.toString(); } else if (value instanceof Double) { textValue = value.toString(); } else if (value instanceof Long) { textValue = value.toString(); } else if (value instanceof BigDecimal) { textValue = value.toString(); } else if (value instanceof Boolean) { boolean bValue = (Boolean) value; textValue = "是"; if (!bValue) { textValue = "否"; } } else if (value instanceof Date) { Date date = (Date) value; SimpleDateFormat sdf2 = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); textValue = sdf2.format(date); } else if (value instanceof byte[]) { // 有圖片時,設置行高為60px; row.setHeightInPoints(60); // 設置圖片所在列寬度為80px,注意這里單位的一個換算 sheet.setColumnWidth(i, (short) (35.7 * 80)); // sheet.autoSizeColumn(i); byte[] bsValue = (byte[]) value; HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 255, (short) 6, index, (short) 6, index); anchor.setAnchorType(2); patriarch.createPicture(anchor, workbook.addPicture( bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG)); } else { // 其它數據類型都當作字符串簡單處理 if (value != null) { textValue = value.toString(); } } // 如果不是圖片數據,就利用正則表達式判斷textValue是否全部由數字組成 if (textValue != null) { Pattern p = Pattern.compile("^//d+(//.//d+)?{1}quot"); Matcher matcher = p.matcher(textValue); if (matcher.matches()) { // 是數字當作double處理 cell.setCellValue(Double.parseDouble(textValue)); } else { HSSFRichTextString richString = new HSSFRichTextString(textValue); // font3.setColor(HSSFColor.BLUE.index); // richString.applyFont(font3); cell.setCellValue(richString); } } } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } finally { // 清理資源 } } } // 輸出流 OutputStream out = null; try { response.setContentType("application/vnd.ms-excel; charset=utf-8"); response.setHeader("Content-Disposition", "attachment;filename="+ java.net.URLEncoder.encode(fileName + ".xls", "UTF-8")); response.setCharacterEncoding("utf-8"); out = response.getOutputStream(); workbook.write(out); } catch (IOException e) { e.printStackTrace(); } finally { out.flush(); out.close(); } } // 遞歸調用,獲取多層包裝類中的值 private Object getValue(Object obj, String colField) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, ClassNotFoundException { Object value = null; if (colField.indexOf(".") > 0) { String fieldName = colField.substring(0, colField.indexOf(".")); Field field = obj.getClass().getDeclaredField(fieldName); Class<?> clazz = Class.forName(field.getType().getName()); field.setAccessible(true); Object fieldObj = field.get(obj); String nextField = colField.substring(colField.indexOf(".") + 1); value = getValue(fieldObj, nextField); } else { Field field = obj.getClass().getDeclaredField(colField); field.setAccessible(true); value = field.get(obj); } return value; }
使用excel導出功能完整例子如下,直接在controller中完成,代碼很簡潔:
@RequestMapping(value="/exportProductExpiredReport",method=RequestMethod.POST) public void exportProductExpiredReport(ProductVo vo,HttpServletResponse response) throws Exception{ List<TProduct> list = productService.getProductExpiredList(vo); String colName = "RR商品編碼,規格型號,商品名稱,單位,產品類別,批准文號,有效期,備注"; String columnFieldStr = "ptCode,ptRuleModel,ptName,um.umUm1,proType.typeName,ptPemissionNO,ptExpiryDate,ptRemark"; ExcelUtil excel = new ExcelUtil(); excel.exportExcelNew("商品許可到期報表", colName, columnFieldStr, list, response); }
今天七夕,祝天下有情人終成眷屬。