SpringBoot集成文件 - 集成POI之Excel导入导出
Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程序对Microsoft Office格式档案读和写的功能。本文主要介绍通过SpringBoot集成POI工具实现Excel的导入和导出功能。@pdai
知识准备
需要了解POI工具,以及POI对Excel中的对象的封装对应关系。
什么是POI
Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程序对Microsoft Office格式档案读和写的功能。POI为“Poor Obfuscation Implementation”的首字母缩写,意为“简洁版的模糊实现”。
Apache POI 是创建和维护操作各种符合Office Open XML(OOXML)标准和微软的OLE 2复合文档格式(OLE2)的Java API。用它可以使用Java读取和创建,修改MS Excel文件.而且,还可以使用Java读取和创建MS Word和MSPowerPoint文件。更多请参考官方文档。
POI中基础概念
生成xls和xlsx有什么区别?POI对Excel中的对象的封装对应关系?
生成xls和xlsx有什么区别呢?
| XLS | XLSX |
|---|---|
| 只能打开xls格式,无法直接打开xlsx格式 | 可以直接打开xls、xlsx格式 |
| 只有65536行、256列 | 可以有1048576行、16384列 |
| 占用空间大 | 占用空间小,运算速度也会快一点 |
POI对Excel中的对象的封装对应关系如下:
| Excel | POI XLS | POI XLSX(Excel 2007+) |
|---|---|---|
| Excel 文件 | HSSFWorkbook (xls) | XSSFWorkbook(xlsx) |
| Excel 工作表 | HSSFSheet | XSSFSheet |
| Excel 行 | HSSFRow | XSSFRow |
| Excel 单元格 | HSSFCell | XSSFCell |
| Excel 单元格样式 | HSSFCellStyle | HSSFCellStyle |
| Excel 颜色 | HSSFColor | XSSFColor |
| Excel 字体 | HSSFFont | XSSFFont |
实现案例
这里展示SpringBoot集成POI导出用户列表的和导入用户列表的例子。
Pom依赖
引入poi的依赖包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.2</version>
</dependency>
导出Excel
UserController中导出的方法
@ApiOperation("Download Excel")
@GetMapping("/excel/download")
public void download(HttpServletResponse response) {
try {
SXSSFWorkbook workbook = userService.generateExcelWorkbook();
response.reset();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition",
"attachment;filename=user_excel_" + System.currentTimeMillis() + ".xlsx");
OutputStream os = response.getOutputStream();
workbook.write(os);
workbook.dispose();
} catch (Exception e) {
e.printStackTrace();
}
}
UserServiceImple中导出Excel的主方法
private static final int POSITION_ROW = 1;
private static final int POSITION_COL = 1;
/**
* @return SXSSFWorkbook
*/
@Override
public SXSSFWorkbook generateExcelWorkbook() {
SXSSFWorkbook workbook = new SXSSFWorkbook();
Sheet sheet = workbook.createSheet();
int rows = POSITION_ROW;
int cols = POSITION_COL;
// 表头
Row head = sheet.createRow(rows++);
String[] columns = new String[]{"ID", "Name", "Email", "Phone", "Description"};
int[] colWidths = new int[]{2000, 3000, 5000, 5000, 8000};
CellStyle headStyle = getHeadCellStyle(workbook);
for (int i = 0; i < columns.length; ++i) {
sheet.setColumnWidth(cols, colWidths[i]);
addCellWithStyle(head, cols++, headStyle).setCellValue(columns[i]);
}
// 表内容
CellStyle bodyStyle = getBodyCellStyle(workbook);
for (User user : getUserList()) {
cols = POSITION_COL;
Row row = sheet.createRow(rows++);
addCellWithStyle(row, cols++, bodyStyle).setCellValue(user.getId());
addCellWithStyle(row, cols++, bodyStyle).setCellValue(user.getUserName());
addCellWithStyle(row, cols++, bodyStyle).setCellValue(user.getEmail());
addCellWithStyle(row, cols++, bodyStyle).setCellValue(String.valueOf(user.getPhoneNumber()));
addCellWithStyle(row, cols++, bodyStyle).setCellValue(user.getDescription());
}
return workbook;
}
private Cell addCellWithStyle(Row row, int colPosition, CellStyle cellStyle) {
Cell cell = row.createCell(colPosition);
cell.setCellStyle(cellStyle);
return cell;
}
private List<User> getUserList() {
return Collections.singletonList(User.builder()
.id(1L).userName("pdai").email("pdai@pdai.tech").phoneNumber(121231231231L)
.description("hello world")
.build());
}
private CellStyle getHeadCellStyle(Workbook workbook) {
CellStyle style = getBaseCellStyle(workbook);
// fill
style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
return style;
}
private CellStyle getBodyCellStyle(Workbook workbook) {
return getBaseCellStyle(workbook);
}
private CellStyle getBaseCellStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
// font
Font font = workbook.createFont();
font.setBold(true);
style.setFont(font);
// align
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.TOP);
// border
style.setBorderBottom(BorderStyle.THIN);
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderLeft(BorderStyle.THIN);
style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderRight(BorderStyle.THIN);
style.setRightBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderTop(BorderStyle.THIN);
style.setTopBorderColor(IndexedColors.BLACK.getIndex());
return style;
}
导出后的excel如下

导入Excel
我们将上面导出的excel文件导入。
UserController中导入的方法
@ApiOperation("Upload Excel")
@PostMapping("/excel/upload")
public ResponseResult<String> upload(@RequestParam(value = "file", required = true) MultipartFile file) {
try {
userService.upload(file.getInputStream());
} catch (Exception e) {
e.printStackTrace();
return ResponseResult.fail(e.getMessage());
}
return ResponseResult.success();
}
UserServiceImple中导入Excel的主方法
@Override
public void upload(InputStream inputStream) throws IOException {
XSSFWorkbook book = new XSSFWorkbook(inputStream);
XSSFSheet sheet = book.getSheetAt(0);
// add some validation here
// parse data
int cols;
for (int i = POSITION_ROW; i < sheet.getLastRowNum(); i++) {
XSSFRow row = sheet.getRow(i + 1); // 表头不算
cols = POSITION_COL;
User user = User.builder()
.id(getCellLongValue(row.getCell(cols++)))
.userName(getCellStringValue(row.getCell(cols++)))
.email(getCellStringValue(row.getCell(cols++)))
.phoneNumber(Long.parseLong(getCellStringValue(row.getCell(cols++))))
.description(getCellStringValue(row.getCell(cols++)))
.build();
log.info(user.toString());
}
book.close();
}
private String getCellStringValue(XSSFCell cell) {
try {
if (null!=cell) {
return String.valueOf(cell.getStringCellValue());
}
} catch (Exception e) {
return String.valueOf(getCellIntValue(cell));
}
return "";
}
private long getCellLongValue(XSSFCell cell) {
try {
if (null!=cell) {
return Long.parseLong("" + (long) cell.getNumericCellValue());
}
} catch (Exception e) {
e.printStackTrace();
}
return 0L;
}
private int getCellIntValue(XSSFCell cell) {
try {
if (null!=cell) {
return Integer.parseInt("" + (int) cell.getNumericCellValue());
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
通过PostMan进行接口测试

执行接口后,后台的日志如下
2022-06-10 21:36:01.720 INFO 15100 --- [nio-8080-exec-2] t.p.s.f.e.p.s.impl.UserServiceImpl : User(id=1, userName=pdai, email=pdai@pdai.tech, phoneNumber=121231231231, description=hello world)
示例源码
https://github.com/realpdai/tech-pdai-spring-demos
参考文章
https://poi.apache.org/index.html
更多内容
告别碎片化学习,无套路一站式体系化学习后端开发: Java 全栈知识体系(https://pdai.tech)
SpringBoot集成文件 - 集成POI之Excel导入导出的更多相关文章
- Java之POI的excel导入导出
一.Apache POI是一种流行的API,它允许程序员使用Java程序创建,修改和显示MS Office文件.这由Apache软件基金会开发使用Java分布式设计或修改Microsoft Offic ...
- 基于POI的Excel导入导出(JAVA实现)
今天做了个excel的导入导出功能,在这记录下. 首先现在相关poi的相关jar包,资源链接:http://download.csdn.net/detail/opening_world/9663247 ...
- Spring Boot学习笔记----POI(Excel导入导出)
业务:动态生成模板导出Excel,用户修改完再导入Excel. Spring boot + bootstrap + poi 1.添加Dependence <dependency> < ...
- 【原创】POI操作Excel导入导出工具类ExcelUtil
关于本类线程安全性的解释: 多数工具方法不涉及共享变量问题,至于添加合并单元格方法addMergeArea,使用ThreadLocal变量存储合并数据,ThreadLocal内部借用Thread.Th ...
- POI实现Excel导入导出
我们知道要创建一张excel你得知道excel由什么组成,比如说sheet也就是一个工作表格,例如一行,一个单元格,单元格格式,单元格内容格式…这些都对应着poi里面的一个类. 一个excel表格: ...
- apache POI 操作excel<导入导出>
1.首先导入maven依赖 <!-- POI核心依赖 --> <dependency> <groupId>org.apache.poi</groupId> ...
- 一个基于POI的通用excel导入导出工具类的简单实现及使用方法
前言: 最近PM来了一个需求,简单来说就是在录入数据时一条一条插入到系统显得非常麻烦,让我实现一个直接通过excel导入的方法一次性录入所有数据.网上关于excel导入导出的例子很多,但大多相互借鉴. ...
- poi excel导入导出
pom <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artif ...
- Excel导入导出工具(简单、好用且轻量级的海量Excel文件导入导出解决方案.)
Excel导入导出工具(简单.好用且轻量级的海量Excel文件导入导出解决方案.) 置顶 2019-09-07 16:47:10 $9420 阅读数 261更多 分类专栏: java 版权声明:本 ...
随机推荐
- 文件传输协议:FTP、TFTP、SFTP有什么区别?
一个执着于技术的公众号 FTP 提供一种在服务器和客户机之间上传和下载文件的有效方式:是基于TCP的传输,FTP采用双TCP连接方式:支持授权与认证机制,提供目录列表功能. ---控制连接使用TCP端 ...
- Windows Terminal无法加载WSL [process exited with code 4294967295 (0xffffffff)]
在Windows Terminal中WSL无法打开错误代码是 process exited with code 4294967295 (0xffffffff),但在命令行中 通过 "C:\W ...
- 探索ABP的EventHub解决方案
在上一章中,我们构建了一个简单的全栈 Web 应用程序,我们已经看到了使用 ABP 框架开发应用的典型流程,在接下来,我们将使用 ABP 框架创建更高级的应用程序. 给出具有现实世界复杂性的例子并不容 ...
- 一、深入学习c++先要练好的内功
掌握进程虚拟地址空间区域的划分 课程讲的内容建立在x86 32位的Linux系统下. 任何的编程语言会产生两种东西:指令和数据.磁盘上的可执行文件在启动时都会加载到内存当中,但是不会加载到物理内存中, ...
- 我怀疑这是IDEA的BUG,但是我翻遍全网没找到证据!
你好呀,我是歪歪. 前几天有朋友给我发来这样的一个截图: 他说他不理解,为什么这样不报错. 我说我也不理解,把一个 boolean 类型赋值给 int 类型,怎么会不报错呢,并接着追问他:这个代码截图 ...
- SpringBoot Redis 实践指南
前言 SpringBoot Cache 是一个很好的缓存框架,可以兼容多种缓存实现,数据量较大的情况下,Redis 应该是最多被使用的. 本文重点介绍 SpringBoot 和 Redis 整合使用的 ...
- VMWare中CentOS安装VM-Tools
查看CD-ROM驱动器的设备信息 可以通过下面几个命令来查看 dmesg命令 dmesg | egrep -i --color 'cdrom|dvd|cd/rw|writer' /proc/sys/d ...
- 用 notion 管理信用卡与花呗
用 notion 管理信用卡与花呗 Notion原文,排版更佳 概述 不需要提醒功能和安卓用户可以忽略Scriptable和快捷指令 app的设置 Notion 建立信用卡表格,录入信用卡基本信息,自 ...
- Fail2ban 安装Fail2ban到Ubuntu
系统版本:Ubuntu 16.04.5 LTS 软件版本:fail2ban-0.9.3 硬件要求:无 1.安装Fail2ban root@local:~# apt-get update root@lo ...
- ML第4周学习小结
本周收获 总结一下本周学习内容: 1.学习了<深入浅出Pandas>的第五章:Pandas高级操作的两个内容 添加修改数据 高级过滤 我的博客链接: Pandas:添加修改.高级过滤 2. ...