Java导出Excel

来源:互联网 发布:网络玄学是什么意思 编辑:程序博客网 时间:2024/06/14 23:29
1.创建Excel文件 2.创建工作薄 3.创建sheet 4.用数组存表头  5.第一行设置列名  6.追加数据   7.关闭数据流
 public void handOverReport(SysRubbishVo sysRubbishVo, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer rows, String sort, String order, HttpServletRequest request, HttpSession httpSession,HttpServletResponse response) throws IOException, BiffException, WriteException {   PageInfo pageInfo = new PageInfo(page, rows, sort, order);   Map<String, Object> condition = ServletUtils.getParmFilter(request);   String date = null;   date = DateUtils.getDate();   List<SysRubbishDataVo> sysRubbishDataVos = sysRubbishDataService.findDataGrid(pageInfo, condition,date);   String[] title = {"日期","姓名","性别","部门"};   //创建Excel工作簿   HSSFWorkbook workbook = new HSSFWorkbook();   //创建一个工作表sheet   HSSFSheet sheet = workbook.createSheet();   //创建第一行   HSSFRow row = sheet.createRow(0);   HSSFCell cell = null;   //插入第一行数据 id,name,sex   for (int i = 0; i < title.length; i++) {      cell = row.createCell(i);      cell.setCellValue(title[i]);   }   //追加数据   for (int i = 0; i < sysRubbishDataVos.size(); i++) {      HSSFRow nextrow = sheet.createRow(i+1);      HSSFCell cell2 = nextrow.createCell(0);      cell2.setCellValue(sysRubbishDataVos.get(i).getRecycleTime());      cell2 = nextrow.createCell(1);      cell2.setCellValue(sysRubbishDataVos.get(i).getRubType());//垃圾类型      cell2 = nextrow.createCell(2);      cell2.setCellValue(sysRubbishDataVos.get(i).getTecSign());//垃圾类型   }   //创建一个文件   File file = File.createTempFile("登记表" + System.currentTimeMillis(), ".xls");   try {      file.createNewFile();      //将Excel内容存盘      FileOutputStream stream = FileUtils.openOutputStream(file);      workbook.write(stream);      stream.flush();      stream.close();      response.setContentType("application/x-xls");      response.addHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(file.getName(), "utf-8") + "\"");      response.setContentLength((int) file.length()); // 文件大小      i2o(new BufferedInputStream(new FileInputStream(file)), response.getOutputStream());      // 最后删除这个临时文件      file.deleteOnExit();   } catch (IOException e) {      e.printStackTrace();   }}
原创粉丝点击