把日志从数据库导出到Excel表格中(poi)

前台页面

1 <div class="padding border-bottom">
2             <a href="download" class="button border-blue"
3             >下载</a>
4             </div>
View Code

后台代码

 1     @RequestMapping("download")
 2     
 3     public void download(HttpServletResponse resp,HttpServletRequest req) throws IOException{
 4         try {
 5         req.setCharacterEncoding("UTF-8");
 6         resp.setContentType("text/html;charset=UTF-8");
 7         String outputFile="F:\\outFile\\outFile.xls"; 
 8         HSSFWorkbook workbook = new HSSFWorkbook();
 9         HSSFSheet sheet = workbook.createSheet();
10         workbook.setSheetName(0, "demo");
11         HSSFRow row = sheet.createRow((int)0);
12         HSSFCellStyle style = workbook.createCellStyle();
13         style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
14         String [] excelHeader = {"日志编号","操作人","操作内容","时间"};
15         for (int i = 0; i < excelHeader.length; i++) {
16             HSSFCell cell = row.createCell(i);
17             cell.setCellValue(excelHeader[i]);
18             cell.setCellStyle(style);
19 //            sheet.autoSizeColumn(i);
20         }
21         List<Log> logs = logService.selectLogs();
22         for (int i = 0; i < logs.size(); i++) {
23             Log log = logs.get(i);
24             HSSFRow hssfRow = sheet.createRow(i+1);
25             hssfRow.createCell(0).setCellValue(log.getId());
26             hssfRow.createCell(1).setCellValue(log.getUserName());
27             hssfRow.createCell(2).setCellValue(log.getMethod());
28             hssfRow.createCell(3).setCellValue(log.getTime());
29             sheet.autoSizeColumn(i);
30         }
31         
32             FileOutputStream fos = new FileOutputStream(outputFile);
33             workbook.write(fos);
34             fos.close();
35         } catch (FileNotFoundException e) {
36             // TODO Auto-generated catch block
37             e.printStackTrace();
38         } catch (IOException e) {
39             // TODO Auto-generated catch block
40             e.printStackTrace();
41         }
42         resp.getWriter().print("导出日志成功!");
43     }
View Code

截图

猜你喜欢

转载自www.cnblogs.com/xaoco/p/9121464.html