工具类: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"; }