系统城装机大师 - 固镇县祥瑞电脑科技销售部宣传站!

当前位置:首页 > server > anz > 详细页面

Java使用Apache.POI中HSSFWorkbook导出到Excel的实现方法

时间:2021-04-07来源:www.pcxitongcheng.com作者:电脑系统城

使用Apache.POI中HSSFWorkbook导出到Excel,具体内容如下所示:

1.引入Poi依赖(3.12)

依赖如下:

1
2
3
4
5
<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi</artifactId>
   <version>3.12</version>
</dependency>

2.创建实体类(User.java)

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
package com.kd.nm.entity.pojo;
 
/**
 * 实体类(User)
 *
 * author 小辰哥哥
 */
public class User {
 // 用户编号
 private String userNo;
 // 用户名称
 private String userName;
 // 年龄
 private String age;
 
 // 无参构造
 public User() {
 }
 
 // 有参构造
 public User(String userNo, String userName, String age) {
  this.userNo = userNo;
  this.userName = userName;
  this.age = age;
 }
 
 // get与set方法进行封装
 public String getUserNo() {
  return userNo;
 }
 
 public void setUserNo(String userNo) {
  this.userNo = userNo;
 }
 
 public String getUserName() {
  return userName;
 }
 
 public void setUserName(String userName) {
  this.userName = userName;
 }
 
 public String getAge() {
  return age;
 }
 
 public void setAge(String age) {
  this.age = age;
 }
 
 // 重新toString方法
 @Override
 public String toString() {
  return "User{" +
    "userNo='" + userNo + '\'' +
    ", userName='" + userName + '\'' +
    ", age='" + age + '\'' +
    '}';
 }
}

3.Excel相关工具类(ExcelUtil、ReflectUtil)

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
package com.kd.nm.util;
 
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.*;
 
/**
 * Description : Excel相关工具类
 *
 * @author: 小辰哥哥
 *
 */
public class ExcelUtil {
 
 /**
  * 生成excel表格
  * @param heads 表头内容
  * @param data 数据内容
  * @return
  */
 public static HSSFWorkbook creatExcel(Map<String, String> heads, List data) {
 
  // 声明一个工作薄
  HSSFWorkbook workbook = new HSSFWorkbook();
  // 生成一个表格
  HSSFSheet sheet = workbook.createSheet();
 
  // 生成标题行样式
  HSSFCellStyle headStyle = creatStyle(workbook, (short) 14);
 
  // 生成表格内容样式
  HSSFCellStyle bodyStyle = creatStyle(workbook, (short) 10);
 
  // 标题元素
  List<String> keys = new ArrayList<String>(heads.keySet());
 
  // 像素单位
  short px = 1000;
  // 设置列宽
  for (int columnIndex = 0; columnIndex < keys.size(); columnIndex++) {
 
   sheet.setColumnWidth(columnIndex, 6 * px);
  }
 
  // 生成表格
  for (int rowNum = 0; rowNum <= data.size(); rowNum++) {
 
   // 创建行
   HSSFRow row = sheet.createRow(rowNum);
 
   for (int cellNum = 0; cellNum < keys.size(); cellNum++) {
 
    // 创建列
    HSSFCell cell = row.createCell(cellNum);
 
    // 标题
    if (rowNum == 0) {
 
     cell.setCellStyle(headStyle);
     cell.setCellValue(heads.get(keys.get(cellNum)));
    } else { // 内容
 
     cell.setCellStyle(bodyStyle);
     // 通过反射获取
     cell.setCellValue(ReflectUtil.getValue(keys.get(cellNum), data.get(rowNum - 1)));
    }
   }
  }
 
  return workbook;
 }
 
 /**
  * 生成样式
  * @param workbook
  * @param size
  * @return
  */
 public static HSSFCellStyle creatStyle(HSSFWorkbook workbook, short size) {
 
  HSSFCellStyle style = workbook.createCellStyle();
  style.setAlignment((HSSFCellStyle.ALIGN_CENTER));
  style.setVerticalAlignment((HSSFCellStyle.VERTICAL_CENTER));
  HSSFFont font = workbook.createFont();
  font.setFontHeightInPoints(size);
  font.setFontName("微软雅黑");
  style.setFont(font);
  style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  style.setBorderTop(HSSFCellStyle.BORDER_THIN);
  style.setBorderRight(HSSFCellStyle.BORDER_THIN);
  style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
 
  return style;
 }
}
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
package com.kd.nm.util;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
 
/**
 * 反射工具包
 *
 * @author: 小辰哥哥
 */
public class ReflectUtil {
 
 private static final Logger logger = LoggerFactory.getLogger(ReflectUtil.class);
 
 public static String getValue(String key, Object obj) {
 
  String value = "";
 
  try {
 
   // 获取当前属性
   PropertyDescriptor pd = new PropertyDescriptor(key, obj.getClass());
   // 获取get方法
   Method getMd = pd.getReadMethod();
   value = getMd.invoke(obj).toString();
  } catch (Exception e) {
 
   logger.error("获取内容失败!");
   e.printStackTrace();
  }
 
  return value;
 }
 
 public static void setValue(String key, String value, Object obj) {
 
  try {
 
   // 获取当前属性
   PropertyDescriptor pd = new PropertyDescriptor(key, obj.getClass());
   // 获取set方法
   Method writeMd = pd.getWriteMethod();
   writeMd.invoke(obj, value);
  } catch (Exception e) {
 
   logger.error("设置内容失败!");
   e.printStackTrace();
  }
 }
}

4.后端控制器代码

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
@RequestMapping(value = "/exportExcel",method = RequestMethod.GET,produces = "application/json")
 public void exportExcel(HttpServletResponse httpServletResponse) throws IOException {
 
  // 表头内容(可在前端设置,通过参数传递进来) Key是实体类的属性值,value是表头的lable
  Map<String,String> head = new HashMap<>();
  head.put("userNo","用户编号");
  head.put("userName","用户名称");
  head.put("age","年龄");
 
  // 表格数据内容,模拟数据库查询出来的数据
  List<User> data = new ArrayList<>();
  data.add(new User("1","小辰哥哥","18"));
  data.add(new User("2","小猪妹妹","18"));
  data.add(new User("3","大猪哥哥","18"));
   
   
  // 生成工作薄
  HSSFWorkbook hssfWorkbook = ExcelUtil.creatExcel(head, data);
 
  // 定义文件名
  String fileName = "导出Excel表格";
 
  httpServletResponse.setHeader("Cache-Control", "max-age=0");
  httpServletResponse.setContentType("application/vnd.ms-excel");
  httpServletResponse.addHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"),
    "ISO-8859-1") + ".xls");
 
  OutputStream outputStream = httpServletResponse.getOutputStream();
 
  hssfWorkbook.write(outputStream);
  outputStream.flush();
  outputStream.close();
 }

5.访问映射地址

接口访问:

http://localhost:9090/FaultTreatment/api/standard/exportExcel

在这里插入图片描述
在这里插入图片描述

到此这篇关于Java使用Apache.POI中HSSFWorkbook导出到Excel的实现方法的文章就介绍到这了

分享到:

相关信息

系统教程栏目

栏目热门教程

人气教程排行

站长推荐

热门系统下载