poi-生成excel文档并返还给浏览器
处理请求代码
public void exportExcel(HttpServletRequest req, HttpServletResponse resp) throws IOException {//1.设置响应类型resp.setContentType("application/vnd.ms-excel");resp.setHeader("Content-Disposition","attachment;filename=\"duty.xls\"");//2.获取请求参数//3.得到响应数据DutyService service = new DutyServiceImpl();List<Duty> duties = service.selectAll();//4.做出响应ArrayList<String> cols = new ArrayList<>();cols.add("用户名");cols.add("真实姓名");cols.add("所属部门");cols.add("出勤日期");cols.add("签到时间");cols.add("签退时间");ExcelUtil.exportExcel(duties,cols,resp.getOutputStream());}
导出excel代码
public static void exportExcel(List<Duty> data, List<String> colNames, OutputStream outputStream ){// 创建一个Excel文件HSSFWorkbook workbook = new HSSFWorkbook();// 创建一个工作表HSSFSheet sheet = workbook.createSheet("考勤信息表");// 添加表头行HSSFRow hssfRow = sheet.createRow(0);// 设置单元格格式居中HSSFCellStyle cellStyle = workbook.createCellStyle();cellStyle.setAlignment(HorizontalAlignment.CENTER);// 添加表头内容for(int i=0; i<colNames.size();i++){HSSFCell headCell = hssfRow.createCell(i);headCell.setCellValue(colNames.get(i));headCell.setCellStyle(cellStyle);}// 添加数据内容for (int i = 0; i < data.size(); i++) {hssfRow = sheet.createRow((int) i + 1);Duty duty = data.get(i);// 创建单元格,并设置值HSSFCell cell = hssfRow.createCell(0);cell.setCellValue(duty.getEmprid());cell.setCellStyle(cellStyle);cell = hssfRow.createCell(1);cell.setCellValue(duty.getEmployee().getRealname());cell.setCellStyle(cellStyle);cell = hssfRow.createCell(2);cell.setCellValue(duty.getDept().getDeptname());cell.setCellStyle(cellStyle);cell = hssfRow.createCell(3);cell.setCellValue(duty.getDtdate());cell.setCellStyle(cellStyle);cell = hssfRow.createCell(4);cell.setCellValue(duty.getSignintime());cell.setCellStyle(cellStyle);cell = hssfRow.createCell(5);cell.setCellValue(duty.getSignouttime());cell.setCellStyle(cellStyle);}// 保存Excel文件try {workbook.write(outputStream);outputStream.close();} catch (Exception e) {e.printStackTrace();}}