导出excel是咱Java开发的必备技能啦,之前项目有这个功能,现在将其独立出来,分享一下。
所用技术就是SpringBoot,然后是MVC架构模式。
废话不多说,直接上代码了,源码点末尾链接就可以下载。
(1)新建一个SpringBoot项目(可以官网https://start.spring.io/直接生成下载,然后导入eclipse),项目结构如下:

(2)修改pom文件,添加依赖;

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<!-- 导出excel -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-contrib -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-contrib</artifactId>
<version>3.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.17</version>
</dependency>
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
(3)新建一个实体类,命名为User.java;

package com.twf.springcloud.ExportExcel.po;
import java.io.Serializable;
public class User implements Serializable{
private static final long serialVersionUID = -9180229310895087286L;
private String name; // 姓名
private String sex; // 性别
private Integer age; // 年龄
private String phoneNo; // 手机号
private String address; // 地址
private String hobby; // 爱好
public User(String name, String sex, Integer age, String phoneNo, String address, String hobby) {
super();
this.name = name;
this.sex = sex;
this.age = age;
this.phoneNo = phoneNo;
this.address = address;
this.hobby = hobby;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
@Override
public String toString() {
return "User [name=" + name + ", sex=" + sex + ", age=" + age + ", phoneNo=" + phoneNo + ", address=" + address
+ ", hobby=" + hobby + "]";
}
}
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
(4)新建一个excel样式工具类;

package com.twf.springcloud.ExportExcel.utils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
/**
* excle样式工具类
*/
public class ExcelFormatUtil {
/**
* 设置报表头样式
* @param workbook
* @return
*/
public static CellStyle headSytle(SXSSFWorkbook workbook){
// 设置style1的样式,此样式运用在第二行
CellStyle style1 = workbook.createCellStyle();// cell样式
// 设置单元格背景色,设置单元格背景色以下两句必须同时设置
style1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);// 设置填充样式
style1.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);// 设置填充色
// 设置单元格上、下、左、右的边框线
style1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style1.setBorderRight(HSSFCellStyle.BORDER_THIN);
style1.setBorderTop(HSSFCellStyle.BORDER_THIN);
Font font1 = workbook.createFont();// 创建一个字体对象
font1.setBoldweight((short) 10);// 设置字体的宽度
font1.setFontHeightInPoints((short) 10);// 设置字体的高度
font1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 粗体显示
style1.setFont(font1);// 设置style1的字体
style1.setWrapText(true);// 设置自动换行
style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 设置单元格字体显示居中(左右方向)
style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 设置单元格字体显示居中(上下方向)
return style1;
}
/**
* 设置报表体样式
* @param wb
* @return
*/
public static CellStyle contentStyle(SXSSFWorkbook wb){
// 设置style1的样式,此样式运用在第二行
CellStyle style1 = wb.createCellStyle();// cell样式
// 设置单元格上、下、左、右的边框线
style1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style1.setBorderRight(HSSFCellStyle.BORDER_THIN);
style1.setBorderTop(HSSFCellStyle.BORDER_THIN);
style1.setWrapText(true);// 设置自动换行
style1.setAlignment(HSSFCellStyle.ALIGN_LEFT);// 设置单元格字体显示居中(左右方向)
style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 设置单元格字体显示居中(上下方向)
return style1;
}
/**
* 设置报表标题样式
* @param workbook
* @return
*/
public static HSSFCellStyle titleSytle(HSSFWorkbook workbook,short color,short fontSize){
// 设置style1的样式,此样式运用在第二行
HSSFCellStyle style1 = workbook.createCellStyle();// cell样式
// 设置单元格背景色,设置单元格背景色以下两句必须同时设置
//style1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);// 设置填充样式
//short fcolor = color;
if(color != HSSFColor.WHITE.index){
style1.setFillForegroundColor(color);// 设置填充色
}
// 设置单元格上、下、左、右的边框线
style1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style1.setBorderRight(HSSFCellStyle.BORDER_THIN);
style1.setBorderTop(HSSFCellStyle.BORDER_THIN);
HSSFFont font1 = workbook.createFont();// 创建一个字体对象
font1.setBoldweight(fontSize);// 设置字体的宽度
font1.setFontHeightInPoints(fontSize);// 设置字体的高度
font1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 粗体显示
style1.setFont(font1);// 设置style1的字体
style1.setWrapText(true);// 设置自动换行
style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 设置单元格字体显示居中(左右方向)
style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 设置单元格字体显示居中(上下方向)
return style1;
}
/**
*设置表头
* @param sheet
*/
public static void initTitleEX(SXSSFSheet sheet, CellStyle header,String title[],int titleLength[]) {
SXSSFRow row0 = sheet.createRow(0);
row0.setHeight((short) 800);
for(int j = 0;j<title.length; j++) {
SXSSFCell cell = row0.createCell(j);
//设置每一列的字段名
cell.setCellValue(title[j]);
cell.setCellStyle(header);
sheet.setColumnWidth(j, titleLength[j]);
}
}
}
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
101
102
103
104
(5)新建一个Service接口;

package com.twf.springcloud.ExportExcel.sevice;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.ResponseEntity;
public interface ExportService {
ResponseEntity<byte[]> exportExcel(HttpServletRequest request, HttpServletResponse response);
}
1
2
3
4
5
6
7
(6)新建一个Service接口实现类;

package com.twf.springcloud.ExportExcel.sevice.impl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.twf.springcloud.ExportExcel.controller.BaseFrontController;
import com.twf.springcloud.ExportExcel.po.User;
import com.twf.springcloud.ExportExcel.sevice.ExportService;
import com.twf.springcloud.ExportExcel.utils.ExcelFormatUtil;

@Service
public class ExportServiceImpl implements ExportService{
Logger logger = LoggerFactory.getLogger(ExportServiceImpl.class);

@Override
public ResponseEntity<byte[]> exportExcel(HttpServletRequest request, HttpServletResponse response) {
try {
logger.info(">>>>>>>>>>开始导出excel>>>>>>>>>>");

// 造几条数据
List<User> list = new ArrayList<>();
list.add(new User("唐三藏", "男", 30, "13411111111", "东土大唐", "取西经"));
list.add(new User("孙悟空", "男", 29, "13411111112", "菩提院", "打妖怪"));
list.add(new User("猪八戒", "男", 28, "13411111113", "高老庄", "偷懒"));
list.add(new User("沙悟净", "男", 27, "13411111114", "流沙河", "挑担子"));

BaseFrontController baseFrontController = new BaseFrontController();
return baseFrontController.buildResponseEntity(export((List<User>) list), "用户表.xls");
} catch (Exception e) {
e.printStackTrace();
logger.error(">>>>>>>>>>导出excel 异常,原因为:" + e.getMessage());
}
return null;
}

private InputStream export(List<User> list) {
logger.info(">>>>>>>>>>>>>>>>>>>>开始进入导出方法>>>>>>>>>>");
ByteArrayOutputStream output = null;
InputStream inputStream1 = null;
SXSSFWorkbook wb = new SXSSFWorkbook(1000);// 保留1000条数据在内存中
SXSSFSheet sheet = wb.createSheet();
// 设置报表头样式
CellStyle header = ExcelFormatUtil.headSytle(wb);// cell样式
CellStyle content = ExcelFormatUtil.contentStyle(wb);// 报表体样式

// 每一列字段名
String[] strs = new String[] { "姓名", "性别", "年龄", "手机号", "地址","爱好" };

// 字段名所在表格的宽度
int[] ints = new int[] { 5000, 5000, 5000, 5000, 5000, 5000 };

// 设置表头样式
ExcelFormatUtil.initTitleEX(sheet, header, strs, ints);
logger.info(">>>>>>>>>>>>>>>>>>>>表头样式设置完成>>>>>>>>>>");

if (list != null && list.size() > 0) {
logger.info(">>>>>>>>>>>>>>>>>>>>开始遍历数据组装单元格内容>>>>>>>>>>");
for (int i = 0; i < list.size(); i++) {
User user = list.get(i);
SXSSFRow row = sheet.createRow(i + 1);
int j = 0;

SXSSFCell cell = row.createCell(j++);
cell.setCellValue(user.getName()); // 姓名
cell.setCellStyle(content);

cell = row.createCell(j++);
cell.setCellValue(user.getSex()); // 性别
cell.setCellStyle(content);

cell = row.createCell(j++);
cell.setCellValue(user.getAge()); // 年龄
cell.setCellStyle(content);

cell = row.createCell(j++);
cell.setCellValue(user.getPhoneNo()); // 手机号
cell.setCellStyle(content);

cell = row.createCell(j++);
cell.setCellValue(user.getAddress()); // 地址
cell.setCellStyle(content);

cell = row.createCell(j++);
cell.setCellValue(user.getHobby()); // 爱好
cell.setCellStyle(content);
}
logger.info(">>>>>>>>>>>>>>>>>>>>结束遍历数据组装单元格内容>>>>>>>>>>");
}
try {
output = new ByteArrayOutputStream();
wb.write(output);
inputStream1 = new ByteArrayInputStream(output.toByteArray());
output.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (output != null) {
output.close();
if (inputStream1 != null)
inputStream1.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return inputStream1;
}
}
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
(7)新建一个下载文件的通用controller;

package com.twf.springcloud.ExportExcel.controller;

import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;

@Validated
public class BaseFrontController {

/**
* slf4j 日志 logger
*/
protected final Logger logger = LoggerFactory.getLogger(this.getClass());

/**
* 下载文件,纯SpringMVC的API来完成
*
* @param is 文件输入流
* @param name 文件名称,带后缀名
*
* @throws Exception
*/
public ResponseEntity<byte[]> buildResponseEntity(InputStream is, String name) throws Exception {
logger.info(">>>>>>>>>>>>>>>>>>>>开始下载文件>>>>>>>>>>");
if (this.logger.isDebugEnabled())
this.logger.debug("download: " + name);
HttpHeaders header = new HttpHeaders();
String fileSuffix = name.substring(name.lastIndexOf('.') + 1);
fileSuffix = fileSuffix.toLowerCase();

Map<String, String> arguments = new HashMap<String, String>();
arguments.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
arguments.put("xls", "application/vnd.ms-excel");

String contentType = arguments.get(fileSuffix);
header.add("Content-Type", (StringUtils.hasText(contentType) ? contentType : "application/x-download"));
if(is!=null && is.available()!=0){
header.add("Content-Length", String.valueOf(is.available()));
header.add("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode(name, "UTF-8"));
byte[] bs = IOUtils.toByteArray(is);
logger.info(">>>>>>>>>>>>>>>>>>>>结束下载文件-有记录>>>>>>>>>>");
logger.info(">>>>>>>>>>结束导出excel>>>>>>>>>>");
return new ResponseEntity<>(bs, header, HttpStatus.OK);
}else{
String string="数据为空";
header.add("Content-Length", "0");
header.add("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode(name, "UTF-8"));
logger.info(">>>>>>>>>>>>>>>>>>>>结束下载文件-无记录>>>>>>>>>>");
logger.info(">>>>>>>>>>结束导出excel>>>>>>>>>>");
return new ResponseEntity<>(string.getBytes(), header, HttpStatus.OK);
}
}
}
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
(8)新建一个controller,作为请求的入口;

package com.twf.springcloud.ExportExcel.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.twf.springcloud.ExportExcel.sevice.ExportService;

@RestController
@RequestMapping("/exportExcel/")
public class ExportController {

@Autowired
private ExportService exportService;

// 导出excel
@RequestMapping("exportExcel")
public ResponseEntity<byte[]> exportExcel(HttpServletRequest request, HttpServletResponse response) {
return exportService.exportExcel(request,response);
}
}
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
(9)运行ExportExcelApplication,浏览器访问http://localhost:8080/exportExcel/exportExcel,可以下载excel,打开如下:

(10)项目源码,提取码为:wvfm。
---------------------

Java导出Excel(附完整源码)的更多相关文章

  1. 在WebBrowser中执行javascript脚本的几种方法整理(execScript/InvokeScript/NavigateScript) 附完整源码

    [实例简介] 涵盖了几种常用的 webBrowser执行javascript的方法,详见示例截图以及代码 [实例截图] [核心代码] execScript方式: 1 2 3 4 5 6 7 8 9 1 ...

  2. 单独编译和使用webrtc音频回声消除模块(附完整源码+测试音频文件)

    单独编译和使用webrtc音频降噪模块(附完整源码+测试音频文件) 单独编译和使用webrtc音频增益模块(附完整源码+测试音频文件) 说实话很不想写这篇文章,因为这和我一贯推崇的最好全部编译并使用w ...

  3. 单独编译和使用webrtc音频降噪模块(附完整源码+测试音频文件)

    单独编译和使用webrtc音频增益模块(附完整源码+测试音频文件) 单独编译和使用webrtc音频回声消除模块(附完整源码+测试音频文件) webrtc的音频处理模块分为降噪ns,回音消除aec,回声 ...

  4. 单独编译和使用webrtc音频增益模块(附完整源码+测试音频文件)

    webrtc的音频处理模块分为降噪ns和nsx,回音消除aec,回声控制acem,音频增益agc,静音检测部分.另外webrtc已经封装好了一套音频处理模块APM,如果不是有特殊必要,使用者如果要用到 ...

  5. 基于spring-boot和docker-java实现对docker容器的动态管理和监控[附完整源码下载]

    ​ (我是个封面) docker简介 Docker 是一个开源的应用容器引擎,和传统的虚拟机技术相比,Docker 容器性能开销极低,因此也广受开发者喜爱.随着基于docker的开发者越来越多,doc ...

  6. Android自定义组合控件详细示例 (附完整源码)

    在我们平时的Android开发中,有时候原生的控件无法满足我们的需求,或者经常用到几个控件组合在一起来使用.这个时候,我们就可以根据自己的需求创建自定义的控件了,一般通过继承View或其子类来实现. ...

  7. .NET Core中JWT+Auth2.0实现SSO,附完整源码(.NET6)

    一.简介 单点登录(SingleSignOn,SSO) 指的是在多个应用系统中,只需登录一次,就可以访问其他相互信任的应用系统. JWT Json Web Token,这里不详细描述,简单说是一种认证 ...

  8. Android静态图片人脸识别的完整demo(附完整源码)

    Demo功能:利用android自带的人脸识别进行识别,标记出眼睛和人脸位置.点击按键后进行人脸识别,完毕后显示到imageview上. 第一部分:布局文件activity_main.xml < ...

  9. 微信小程序多图上传/朋友圈传图效果【附完整源码】

    效果图 部分源代码 js文件: var uploadPicture = require('../Frameworks/common.js') //获取应用实例 const app = getApp() ...

随机推荐

  1. Debug : array type has incomplete element type

    array type has incomplete element type extern   struct  SoundReport SoundList[32];     ///// 多写了  st ...

  2. RDS For MySQL 字符集相关说明

    https://help.aliyun.com/knowledge_detail/41706.html?spm=5176.7841698.2.9.F5YjI5 字符序命名规则 字符集相关 MySQL  ...

  3. 一篇文章贯穿ACE各种发送接收组件 1.2版

    TCP通信过程介绍 首先介绍一下socket通信的基本过程:这里先如果有两个家伙在通信,一个是S.还有一个叫C (1)S打开port监听本地的port看看有没有人来连接: (2)与此同一时候C试图去连 ...

  4. kendo AutoComplete实现多筛选条件

    kendo autoComplete 原始情况下是不支持多筛选条件的 $("#autocomplete").kendoAutoComplete({ filter: "co ...

  5. UVa 263 - Number Chains

    题目:给你一个数字n0.将它的每一个位的数字按递增排序生成数a,按递减排序生成数b, 新的数字为n1 = a-b,下次依照相同方法计算n1,知道出现循环,问计算了多少次. 分析:数论.模拟.直接模拟计 ...

  6. 自定cell(XIB)团购思路

    自定cell(XIB)团购思路 步骤一.先解析plist文件,创建model层数据. - (instancetype)initWithDict:(NSDictionary *)dict {     s ...

  7. Codeforces Round #330 (Div. 2) D. Max and Bike 二分

    D. Max and Bike For months Maxim has been coming to work on his favorite bicycle. And quite recently ...

  8. splunk的bucket组织目录——时间序列,按照时间来组织目录

    splunk的bucket组织目录:db_1481515116_1480695302_0db_1481537316_1481532688_1db_1481547598_1481539988_2db_1 ...

  9. 无损压缩算法历史——熵编码是最早出现的,后来才有Lzx这些压缩算法

    Lossless   Entropy type Unary Arithmetic Asymmetric Numeral Systems Golomb Huffman  Adaptive Canonic ...

  10. MySQL 基础 —— 字符串处理

    1. 字符串截取 MySQL 字符串截取函数 常见的 MySQL 截取函数有: LEFT(), RIGHT(), SUBSTRING(), SUBSTRING_INDEX() SUBSTRING() ...