java web 读取数据库数据写入Excel返回浏览器下载

 1 @RequestMapping(value = "/download", method = RequestMethod.GET)
 2     public void downstudents(HttpServletRequest request, HttpServletResponse response) throws IOException {
 3         // 一、从后台拿数据
 4         List<Dept> list = null;
 5         list=ds.list();
 6         try {
 7             // 二、 数据转成excel
 8             request.setCharacterEncoding("UTF-8");
 9             response.setCharacterEncoding("UTF-8");
10             response.setContentType("application/x-download");
11 
12             String fileName = "dept.xls";
13             fileName = URLEncoder.encode(fileName, "UTF-8");
14             response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
15             // 第一步:定义一个新的工作簿
16             HSSFWorkbook wb = new HSSFWorkbook();
17             // 第二步:创建一个Sheet页
18             HSSFSheet sheet = wb.createSheet("deptsheet");
19             HSSFCellStyle style=wb.createCellStyle();
20             style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//设置居中(无效)
21             sheet.setDefaultRowHeight((short) (256));// 设置行高
22             sheet.setColumnWidth(0, 2000);// 设置列宽
23             sheet.setColumnWidth(1, 5000);
24             sheet.setColumnWidth(2, 5500);
25             sheet.setColumnWidth(3, 5500);
26             
27             HSSFFont font = wb.createFont();
28             font.setFontName("宋体");//设置字体
29             font.setFontHeightInPoints((short) 16);//设置文字大小
30             
31             HSSFRow row = sheet.createRow(0);
32             HSSFCell cell = row.createCell(0);
33             cell.setCellValue("序号");
34             cell = row.createCell(1);
35             cell.setCellValue("部门编号");
36             cell = row.createCell(2);
37             cell.setCellValue("部门名称");
38             cell = row.createCell(3);
39             cell.setCellValue("地址");
40 
41             HSSFRow rows;
42             HSSFCell cells;
43             for (int i = 0; i < list.size(); i++) {
44                 // 第三步:在这个sheet页里创建一行
45                 rows = sheet.createRow(i + 1);
46                 // 第四步:在该行创建一个单元格
47                 cells = rows.createCell(0);
48                 // 第五步:在该单元格里设置值
49                 cells.setCellValue(i+1);
50                 cells = rows.createCell(1);
51                 cells.setCellValue(list.get(i).getDeptno());
52                 cells = rows.createCell(2);
53                 cells.setCellValue(list.get(i).getDname());
54                 cells = rows.createCell(3);
55                 cells.setCellValue(list.get(i).getLoc());
56 
57             }
58 
59             OutputStream out = response.getOutputStream();
60             wb.write(out);
61             out.close();
62             wb.cloneSheet(0);
63         } catch (IOException e) {
64             e.printStackTrace();
65         }
66     }
javaCode

 

posted on 2018-09-06 21:18  longlinji  阅读(916)  评论(0编辑  收藏  举报