(该文原创--引用请注明出处 zhnagjieatbky)
该代码是以jdbcTemplate产生的结果集作为参数来调用该方法的
1 /** 2 * 数据导出 3 * @param titles 列标题 4 * @param source 导出数据 5 * @param sheetName 表名 6 * @param width 列宽 7 * @param keys 查询出的字段名 8 * @param response 9 * @throws Exception 10 */ 11 public static void write(String sheetName,String[] titles,int[] width,String[] keys, 12 List<Map<String,Object>> source,HttpServletResponse response,String fileType) throws Exception{ 13 14 int columns = titles.length; 15 Workbook wb = null; 16 if(fileType.equals("*.xls")) 17 wb = new HSSFWorkbook(); 18 else if(fileType.equals("*.xlsx")) 19 wb = new XSSFWorkbook(); 20 CellStyle cs = wb.createCellStyle(); 21 cs.setWrapText(true); 22 CellStyle cs2 = wb.createCellStyle(); 23 cs2.setFillBackgroundColor(IndexedColors.SKY_BLUE.getIndex()); 24 Sheet sheet = wb.createSheet(sheetName); 25 26 Row row = sheet.createRow(0); 27 for(int i=0;i<columns;i++){ 28 sheet.setColumnWidth(i, width[i]*256); 29 Cell titleCell0 = row.createCell(i); 30 titleCell0.setCellValue(titles[i]); 31 titleCell0.setCellStyle(cs2); 32 } 33 int len = source.size(); 34 for(int i = 0;i<len;i++){ 35 Row tempRow = sheet.createRow(i+1); //插入行 36 for(int j=0;j<columns;j++){ 37 Cell tempCell = tempRow.createCell(j); //插入列 38 tempCell.setCellStyle(cs); 39 tempCell.setCellValue((String) source.get(i).get(keys[j])); 40 } 41 } 42 wb.write(response.getOutputStream()); 43 }