工具類:java
import java.io.*; import java.lang.reflect.*; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.text.SimpleDateFormat; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.util.CellRangeAddress; public class ExportExcel { /** * 功能: 導出爲Excel工做簿 * 參數: sheetName[工做簿中的一張工做表的名稱] * 參數: titleName[表格的標題名稱] * 參數: headers[表格每一列的列名] * 參數: dataSet[要導出的數據源] * 參數: resultUrl[導出的excel文件地址] * 參數: pattern[時間類型數據的格式] */ public static void exportExcel(String sheetName,String titleName,String[] headers,Collection<?> dataSet,String resultUrl,String pattern) { doExportExcel(sheetName,titleName,headers,dataSet,resultUrl,pattern); } /** * 功能:真正實現導出 */ private static void doExportExcel(String sheetName,String titleName,String[] headers,Collection<?> dataSet,String resultUrl,String pattern) { // 聲明一個工做薄 HSSFWorkbook workbook = new HSSFWorkbook(); // 生成一個工做表 HSSFSheet sheet = workbook.createSheet(sheetName); // 設置工做表默認列寬度爲20個字節 sheet.setDefaultColumnWidth((short) 20); //在工做表中合併首行並居中 sheet.addMergedRegion(new CellRangeAddress(0,0,0,headers.length-1)); // 建立[標題]樣式 HSSFCellStyle titleStyle = workbook.createCellStyle(); // 設置[標題]樣式 titleStyle.setFillForegroundColor(HSSFColor.LIGHT_BLUE.index); titleStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); titleStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); titleStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN); titleStyle.setBorderRight(HSSFCellStyle.BORDER_THIN); titleStyle.setBorderTop(HSSFCellStyle.BORDER_THIN); titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); //建立[標題]字體 HSSFFont titleFont = workbook.createFont(); //設置[標題]字體 titleFont.setColor(HSSFColor.WHITE.index); titleFont.setFontHeightInPoints((short) 24); titleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 把[標題字體]應用到[標題樣式] titleStyle.setFont(titleFont); // 建立[列首]樣式 HSSFCellStyle headersStyle = workbook.createCellStyle(); // 設置[列首]樣式 headersStyle.setFillForegroundColor(HSSFColor.LIGHT_ORANGE.index); headersStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); headersStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); headersStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN); headersStyle.setBorderRight(HSSFCellStyle.BORDER_THIN); headersStyle.setBorderTop(HSSFCellStyle.BORDER_THIN); headersStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); //建立[列首]字體 HSSFFont headersFont = workbook.createFont(); //設置[列首]字體 headersFont.setColor(HSSFColor.VIOLET.index); headersFont.setFontHeightInPoints((short) 12); headersFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 把[列首字體]應用到[列首樣式] headersStyle.setFont(headersFont); // 建立[表中數據]樣式 HSSFCellStyle dataSetStyle = workbook.createCellStyle(); // 設置[表中數據]樣式 dataSetStyle.setFillForegroundColor(HSSFColor.GOLD.index); dataSetStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); dataSetStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); dataSetStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN); dataSetStyle.setBorderRight(HSSFCellStyle.BORDER_THIN); dataSetStyle.setBorderTop(HSSFCellStyle.BORDER_THIN); dataSetStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); dataSetStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 建立[表中數據]字體 HSSFFont dataSetFont = workbook.createFont(); // 設置[表中數據]字體 dataSetFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL); dataSetFont.setColor(HSSFColor.BLUE.index); // 把[表中數據字體]應用到[表中數據樣式] dataSetStyle.setFont(dataSetFont); //建立標題行-增長樣式-賦值 HSSFRow titleRow = sheet.createRow(0); HSSFCell titleCell = titleRow.createCell(0); titleCell.setCellStyle(titleStyle); titleCell.setCellValue(titleName); // 建立列首-增長樣式-賦值 HSSFRow row = sheet.createRow(1); for (short i = 0; i < headers.length; i++) { @SuppressWarnings("deprecation") HSSFCell cell = row.createCell(i); cell.setCellStyle(headersStyle); HSSFRichTextString text = new HSSFRichTextString(headers[i]); cell.setCellValue(text); } // 建立表中數據行-增長樣式-賦值 Iterator<?> it = dataSet.iterator(); int index = 1; while (it.hasNext()) { index++; row = sheet.createRow(index); Object t = it.next(); // 利用反射,根據javabean屬性的前後順序,動態調用getXxx()方法獲得屬性值 Field[] fields = t.getClass().getDeclaredFields(); for (short i = 0; i < fields.length; i++) { @SuppressWarnings("deprecation") HSSFCell cell = row.createCell(i); cell.setCellStyle(dataSetStyle); Field field = fields[i]; String fieldName = field.getName(); String getMethodName = "get"+ fieldName.substring(0, 1).toUpperCase()+ fieldName.substring(1); try { @SuppressWarnings("rawtypes") Class tCls = t.getClass(); @SuppressWarnings("unchecked") Method getMethod = tCls.getMethod(getMethodName,new Class[] {}); Object value = getMethod.invoke(t, new Object[] {}); // 若是是時間類型,按照格式轉換 String textValue = null; if (value instanceof Date) { Date date = (Date) value; SimpleDateFormat sdf = new SimpleDateFormat(pattern); textValue = sdf.format(date); } else { // 其它數據類型都看成字符串簡單處理 textValue = value.toString(); } // 利用正則表達式判斷textValue是否所有由數字組成 if (textValue != null) { Pattern p = Pattern.compile("^\\d+(\\.\\d+)?$"); Matcher matcher = p.matcher(textValue); if (matcher.matches()) { // 是數字看成double處理 cell.setCellValue(Double.parseDouble(textValue)); } else { // 不是數字作普通處理 cell.setCellValue(textValue); } } OutputStream out=null; try { out = new FileOutputStream(resultUrl); workbook.write(out); } catch (IOException e) { e.printStackTrace(); }finally{ try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } finally { //清理資源 try { workbook.close(); } catch (IOException e) { e.printStackTrace(); } } } } } }
測試類:正則表達式
@Test public void tet(){ String sheetName="repayment"; String titleName="repayment"; String[] headers = { "SqlNo", "ALoan_no", "term_no", "Application_no","PeriodSupply","Principal","Interest","Surplus_principal","EffectiveState","isRepaid","repayment_date" }; //List<Book> dataSet = service.selectBookList(); List<Repayment> queryall = repaymentMapper.queryall(); String resultUrl="E:\\test1.xls"; String pattern="yyyy-MM-dd"; ExportExcel.exportExcel(sheetName, titleName, headers, queryall, resultUrl, pattern); }
controller層代碼apache
@ResponseBody @RequestMapping("/export") public String save() throws Exception { String sheetName="repayment"; String titleName="repayment"; String[] headers = { "SqlNo", "ALoan_no", "term_no", "Application_no","PeriodSupply","Principal","Interest","Surplus_principal","EffectiveState","isRepaid","repayment_date" }; //List<Book> dataSet = service.selectBookList(); List<Repayment> queryall = repaymentMapper.queryall(); String resultUrl="E:\\book1.xls"; String pattern="yyyy-MM-dd"; ExportExcel.exportExcel(sheetName, titleName, headers, queryall, resultUrl, pattern); return "success"; }