JAVA POI导出excel

简介:

1.引入maven 依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<dependency>
             <groupId>org.apache.poi</groupId>
             <artifactId>poi</artifactId>
             <version>${poi.version}</version>
         </dependency>
         <dependency>
             <groupId>org.apache.poi</groupId>
             <artifactId>poi-ooxml</artifactId>
             <version>${poi.version}</version>
         </dependency>
         <dependency>
             <groupId>org.apache.poi</groupId>
             <artifactId>poi-ooxml-schemas</artifactId>
             <version>${poi.version}</version>
         </dependency>

  

2.工具类

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
public  class  ExcelUtils {
     /**
      * @param response
      * @param fileName excel文件名
      * @param headMap  表头map
      * @param dataList 表格数据
      */
     public  static  void  exportXlsx(HttpServletResponse response, String fileName,
                                   Map<String, String> headMap, List<Map<String, Object>> dataList) {
 
         Workbook workbook = exportXlsx(fileName, headMap, dataList);
         response.setContentType( "application/binary;charset=ISO8859_1" );
 
         OutputStream outputStream =  null ;
 
         try  {
             outputStream = response.getOutputStream();
             String fn =  new  String(fileName.getBytes(),  "ISO8859_1" );
             response.setHeader( "Content-disposition" "attachment; filename="  + fn +  ".xlsx" );
             workbook.write(outputStream);
         catch  (Exception e) {
             e.printStackTrace();
         finally  {
             if  (outputStream !=  null ) {
                 try  {
                     outputStream.close();
                 catch  (IOException e) {
                     e.printStackTrace();
                 }
             }
         }
 
     }
 
     /**
      * 导出数据
      *
      * @param headMap
      * @param dataList
      */
     public  static  Workbook exportXlsx(String sheetName, Map<String, String> headMap, List<Map<String, Object>> dataList) {
 
         Workbook workbook =  new  XSSFWorkbook();
 
         Sheet sheet = workbook.createSheet(sheetName);
 
 
         int  rowIndex =  0 , columnIndex =  0 ;
         Set<String> keys = headMap.keySet();
 
         //表头
         Row row = sheet.createRow(rowIndex++);
         for  (String key : keys) {
             Cell cell = row.createCell(columnIndex++);
             cell.setCellValue(headMap.get(key));
         }
 
         //内容
         if  (dataList !=  null  && !dataList.isEmpty()) {
             for  (Map<String, Object> map : dataList) {
                 row = sheet.createRow(rowIndex++);
                 columnIndex =  0 ;
                 for  (String key : keys) {
                     Cell cell = row.createCell(columnIndex++);
                     setCellValue(cell, map.get(key));
                 }
             }
         }
 
         return  workbook;
     }
 
     private  static  void  setCellValue(Cell cell, Object obj) {
         if  (obj ==  null ) {
             return ;
         }
         if  (obj  instanceof  String) {
             cell.setCellValue((String) obj);
         else  if  (obj  instanceof  Date) {
             Date date = (Date) obj;
             if  (date !=  null ) {
                 cell.setCellValue(DateUtils.dfDateTime.format(date));
             }
         else  if  (obj  instanceof  Calendar) {
             Calendar calendar = (Calendar) obj;
             if  (calendar !=  null ) {
                 cell.setCellValue(DateUtils.dfDateTime.format(calendar.getTime()));
             }
         else  if  (obj  instanceof  Timestamp) {
             Timestamp timestamp = (Timestamp) obj;
             if  (timestamp !=  null ) {
                 cell.setCellValue(DateUtils.dfDateTime.format( new  Date(timestamp.getTime())));
             }
         else  if  (obj  instanceof  Double) {
             cell.setCellValue((Double) obj);
         else  {
             cell.setCellValue(obj.toString());
         }
     }
}

  3.controller导出用户数据

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
@RequestMapping ( "/export" )
     public  String export(String username, HttpServletRequest request, HttpServletResponse repsonse) {
         //查询用户数据
         UserQueryDTO queryDTO =  new  UserQueryDTO() {{
             setUsername(username);
         }};
         List<CmsUser> userList = userService.findUser(queryDTO);
 
         //表头
         Map<String, String> headNameMap =  new  LinkedHashMap<String, String>();
         headNameMap.put( "userId" "ID" );
         headNameMap.put( "roleName" "角色" );
         headNameMap.put( "userName" "账号" );
         headNameMap.put( "realName" "姓名" );
         headNameMap.put( "mobile" "电话号码" );
         headNameMap.put( "createDate" "创建时间" );
         headNameMap.put( "status" "状态" );
 
         //表格数据
         List<Map<String, Object>> list =  new  ArrayList<Map<String, Object>>();
         if  (userList !=  null  && userList.size() >  0 ) {
             for  (CmsUser user : userList) {
                 String statusName =  "正常" ;
                 if  (StringUtils.isNotBlank(user.getDeleteFlag()) && user.getDeleteFlag().equals(ConstantHelper.DELETE_FLAG_DELETED)) {
                     statusName =  "删除" ;
                 }
 
                 String createDate =  "" ;
                 if  (user.getCreateDate() !=  null ) {
                     createDate =  new  SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ).format(user.getCreateDate());
                 }
 
                 String roleName =  "" ;
                 Set<CmsRole> roleSet = roleService.findByUserId(user.getUserId());
                 if  (roleSet !=  null  && roleSet.size() >  0 ) {
                     for  (CmsRole r : roleSet) {
                         roleName += r.getName() +  " " ;
                     }
                 }
 
                 Map<String, Object> map =  new  HashMap<String, Object>();
                 map.put( "userId" , user.getUserId());
                 map.put( "roleName" , roleName);
                 map.put( "userName" , user.getUsername());
                 map.put( "realName" , user.getRealName());
                 map.put( "mobile" , user.getMobile());
                 map.put( "createDate" , createDate);
                 map.put( "status" , statusName);
                 list.add(map);
             }
         }
 
         ExcelUtils.exportXlsx(repsonse,  "用户" , headNameMap, list);
         return  null ;
     }

  

 


    本文转自 陈敬(Cathy) 博客园博客,原文链接:http://www.cnblogs.com/janes/p/7596637.html,如需转载请自行联系原作者


相关文章
|
8月前
|
Python
Excel中如何批量重命名工作表与将每个工作表导出到单独Excel文件
本文介绍了如何在Excel中使用VBA批量重命名工作表、根据单元格内容修改颜色,以及将工作表导出为独立文件的方法。同时提供了Python实现导出工作表的代码示例,适用于自动化处理Excel文档。
|
Java API Apache
Java编程如何读取Word文档里的Excel表格,并在保存文本内容时保留表格的样式?
【10月更文挑战第29天】Java编程如何读取Word文档里的Excel表格,并在保存文本内容时保留表格的样式?
1086 5
|
人工智能 自然语言处理 Java
FastExcel:开源的 JAVA 解析 Excel 工具,集成 AI 通过自然语言处理 Excel 文件,完全兼容 EasyExcel
FastExcel 是一款基于 Java 的高性能 Excel 处理工具,专注于优化大规模数据处理,提供简洁易用的 API 和流式操作能力,支持从 EasyExcel 无缝迁移。
3469 65
FastExcel:开源的 JAVA 解析 Excel 工具,集成 AI 通过自然语言处理 Excel 文件,完全兼容 EasyExcel
|
9月前
|
Java 测试技术 数据库
spring号码归属地批量查询,批量查询号码归属地,在线工具,可按省份城市运营商号段分类分开分别导出excel表格
简介:文章探讨Spring Boot项目启动优化策略,通过自定义监听器、异步初始化及分库分表加载优化等手段,将项目启动时间从280秒缩短至159秒,提升约50%,显著提高开发效率。
|
Java BI API
Java Excel报表生成:JXLS库的高效应用
在Java应用开发中,经常需要将数据导出到Excel文件中,以便于数据的分析和共享。JXLS库是一个强大的工具,它基于Apache POI,提供了一种简单而高效的方式来生成Excel报表。本文将详细介绍JXLS库的使用方法和技巧,帮助你快速掌握Java中的Excel导出功能。
597 6
|
数据格式 UED
记录一次NPOI库导出Excel遇到的小问题解决方案
【11月更文挑战第16天】本文记录了使用 NPOI 库导出 Excel 过程中遇到的三个主要问题及其解决方案:单元格数据格式错误、日期格式不正确以及合并单元格边框缺失。通过自定义单元格样式、设置数据格式和手动添加边框,有效解决了这些问题,提升了导出文件的质量和用户体验。
1080 3
|
前端开发
实现Excel文件和其他文件导出为压缩包,并导入
实现Excel文件和其他文件导出为压缩包,并导入
313 1
|
Java API Apache
|
前端开发 Java
基于Java爬取微博数据(二) 正文长文本+导出数据Excel
【5月更文挑战第12天】基于Java爬取微博数据,正文长文本+导出数据Excel
java导出复杂excel
java导出复杂excel