Java poi 导出Excel并下载到客户端,具体内容如下
Maven配置,包含了其他文件格式的依赖,就全贴出来了
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-excelant</artifactId> <version> 3.12 </version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-scratchpad</artifactId> <version> 3.12 </version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version> 3.8 </version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version> 3.8 </version> </dependency> |
Service层
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
@Override public void export(Long sblsh, String excelName, OutputStream out) { try { // 第一步,创建一个webbook,对应一个Excel文件 HSSFWorkbook wb = new HSSFWorkbook(); //生成一个表格 HSSFSheet sheet = wb.createSheet(excelName); // 第三步,在sheet中添加表头第0行 HSSFRow row = sheet.createRow( 0 ); // 第四步,创建单元格,并设置值表头 设置表头居中 HSSFCellStyle style = wb.createCellStyle(); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式 HSSFCell cell = row.createCell( 0 ); cell.setCellStyle(style); Byte kjzz = qyjbxxMapper.getKjzz(sblsh); List<A> record = this .selectBySblsh(sblsh); this .insertData(wb, sheet, row, record, out); } } catch (Exception e) { logger.info(e.getMessage()); } } /** * 导入数据到表格中 * @param wb execl文件 * @param sheet 表格 * @param row 表格行 * @param record 要导出的数据 * @param out 输出流 */ private void insertData(HSSFWorkbook wb,HSSFSheet sheet,HSSFRow row,List<A> record, OutputStream out){ try { row = sheet.createRow( 1 ); for ( int i= 0 ;i<title.length;i++){ row.createCell(i).setCellValue(title[i]); } for ( int i= 0 ;i<record.size();i++){ row = sheet.createRow(i+ 2 ); A data = record.get(i); row.createCell( 0 ).setCellValue(data.getHc()); row.createCell( 1 ).setCellValue(data.getXm()); BigDecimal je = data.getJe(); if (je!= null ){ row.createCell( 2 ).setCellValue(je.doubleValue()); } } //合并单元格,前面2位代表开头结尾行,后面2位代表开头结尾列 CellRangeAddress region = new CellRangeAddress( 0 , 0 , 0 ,title.length- 1 ); sheet.addMergedRegion(region); wb.write(out); out.flush(); out.close(); wb.close(); } catch (Exception e) { logger.info(e.getMessage()); } } |
Controller
1
2
3
4
5
6
7
8
9
10
11
12
|
@RequestMapping ( "/export" ) public void export(Long sblsh, HttpServletRequest request, HttpServletResponse response){ response.setContentType( "octets/stream" ); String excelName = "文件名" ; try { response.addHeader( "Content-Disposition" , "attachment;filename=" + new String(excelName.getBytes( "gb2312" ), "ISO8859-1" )+ ".xls" ); OutputStream out = response.getOutputStream(); aService.export(sblsh,excelName ,out); } catch (Exception e) { e.printStackTrace(); } } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://www.cnblogs.com/zwdx/p/7519342.html