// 导出excel表 @RequestMapping( value = "/downPlan.action", produces = {"application/json;charset=UTF-8"}) @ResponseBody public String gridToExcel(HttpServletRequest request, HttpServletResponse response) { List<CardPiece> datas = cps.showCard(); // 第一步,创建一个webbook,对应一个Excel文件 HSSFWorkbook wb = new HSSFWorkbook(); // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet HSSFSheet sheet = wb.createSheet("可参与复垦农户表"); // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short HSSFRow row = sheet.createRow((int) 0); // 第四步,创建单元格,并设置值表头 设置表头居中 HSSFCellStyle style = wb.createCellStyle(); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式 HSSFCell cell = row.createCell((short) 0); cell.setCellValue("宅基地所在地"); cell.setCellStyle(style); cell = row.createCell((short) 1); cell.setCellValue("户主姓名"); cell.setCellStyle(style); cell = row.createCell((short) 2); cell.setCellValue("户主身份证号"); cell.setCellStyle(style); cell = row.createCell((short) 3); cell.setCellValue("房屋结构"); cell = row.createCell((short) 4); cell.setCellValue("房屋使用时间"); cell.setCellStyle(style); cell = row.createCell((short) 5); cell.setCellValue("所属地类"); cell.setCellStyle(style); cell = row.createCell((short) 6); cell.setCellValue("现状地类"); cell.setCellStyle(style); cell = row.createCell((short) 7); cell.setCellValue("项目编号"); cell.setCellStyle(style); // 第五步,写入实体数据 实际应用中这些数据从数据库得到, for (int i = 0; i < datas.size(); i++) { row = sheet.createRow((int) i + 1); CardPiece cp = (CardPiece) datas.get(i); // 第四步,创建单元格,并设置值 row.createCell((short) 0).setCellValue(cp.getQSDWMC()); row.createCell((short) 1).setCellValue(cp.getDYNHXM()); row.createCell((short) 2).setCellValue(cp.getDYNHSFZ()); row.createCell((short) 3).setCellValue(cp.getFWJG()); row.createCell((short) 4).setCellValue(cp.getFWSYSJ()); row.createCell((short) 5).setCellValue(cp.getDLMC()); row.createCell((short) 6).setCellValue(cp.getSFDYXZSJ()); row.createCell((short) 7).setCellValue(cp.getProjectID()); } // 第六步,将文件存到指定位置 try { path = request.getSession().getServletContext().getRealPath("excel") + "/" + "guihua.xls"; OutputStream os = null; response.reset(); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); response.setContentType("application/octet-stream; charset=utf-8"); try { os = response.getOutputStream(); os.write(FileUtils.readFileToByteArray(new File(path))); os.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } } catch (Exception e) { e.printStackTrace(); } return "{\"success\": true}"; }