SpringBoot+POI报表批量导出
由于servletResponse 获取的输出流对象在一次请求中只能输出一次,所以要想实现批量导出报表,需要将excel文件打包成zip格式然后输出。
好了,废话不多说,上代码。
1. 首先,需要导入引用的包。pom文件如下所示(点击“+”号展开)
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.alan.demo</groupId>
<artifactId>office2007-export</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies> <!-- Web 依赖 -->
<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> <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.ant/ant -->
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.8.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- Spring Boot Maven 插件 -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/libs-snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
</project>
2. Controller 实现
package com.alan.demo.controller; import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.tools.zip.ZipOutputStream;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; import com.alan.demo.util.FileUtil; /**
* export batch Excel files.
*
* */
@RestController
public class DataExportController {
private static final String BASE_PATH = System.getProperty("java.io.tmpdir") + "Resource" + File.separator;
@RequestMapping(value = "/export",method = RequestMethod.GET)
public void export(HttpServletRequest request, HttpServletResponse response) {
ZipOutputStream out = null;
BufferedInputStream bis = null;
InputStream in = null;
String tip = UUID.randomUUID().toString() + File.separator;
try {
createAllWorkbooks(tip);
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + "EXCEL2016.zip");
File tempZip = new File(BASE_PATH + tip + "temp.zip");
FileUtil.createZipFile(new File(BASE_PATH+ tip), new ZipOutputStream(tempZip));
System.out.println("Created ZIP File");
OutputStream os = response.getOutputStream();
in = new FileInputStream(tempZip);
bis = new BufferedInputStream(in);
byte buff[] = new byte[1024];
int i = bis.read(buff);
while (i != -1) {
os.write(buff, 0, buff.length);
os.flush();
i = bis.read(buff);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
FileUtil.deleteDir(BASE_PATH);
}
} /**
* create mock data
*
* */
public List<Workbook> createAllWorkbooks(String tip) {
List<Workbook> workbooks = new ArrayList<>();
OutputStream out = null;
try {
for (int i=0;i<100;i++) {
File tempFile = new File(BASE_PATH + tip + i + ".xlsx");
tempFile.getParentFile().mkdirs();
tempFile.createNewFile();
out = new FileOutputStream(tempFile);
Workbook workbook = new XSSFWorkbook();
workbook.createSheet("summary");
workbook.getSheetAt(0).createRow(0);
Row row = workbook.getSheetAt(0).getRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hello Spring Boot.");
workbooks.add(workbook);
workbook.write(out);
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out!= null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return workbooks;
}
}
3. FileUtil 工具类
package com.alan.demo.util; import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream; import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream; public class FileUtil {
/**
* Compress all .xlsx Files under original path.
*
* */
public static void compress(File original, ZipOutputStream out) {
try {
if (original == null) {
System.err.println("Null original file is not allowed.");
}
if (!original.isFile()) {
File[] files = original.listFiles();
for (File file : files) {
compress(file, out);
}
} else if (original.isFile() && original.getName().endsWith(".xlsx")) { FileInputStream fis = new FileInputStream(original);
int j = 0;
byte[] buffer = new byte[1024];
out.putNextEntry(new ZipEntry(original.getName()));
while ((j = fis.read(buffer)) > 0) {
out.write(buffer, 0, j);
}
fis.close();
out.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} /**
* Delete all files under path.
*
* */
public static boolean deleteDir(String path){
File file = new File(path);
if(!file.exists()){
System.err.println("The dir are not exists!");
return false;
} String[] content = file.list();
for(String name : content){
File temp = new File(path, name);
if(temp.isDirectory()){
deleteDir(temp.getAbsolutePath());
temp.delete();
}else{
if(!temp.delete()){
System.err.println("Failed to delete " + name);
}
}
}
return true;
} /**
* Create zip file
* @param originalFile : the directory contains all files prepared to compress.
* @param ZipOutputStream : ZIP file out put stream
* */
public static void createZipFile(File originalFile, ZipOutputStream out) { FileUtil.compress(originalFile, out);
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} /**
* clone input stream
*
* */
public static ByteArrayOutputStream cloneInputStream(InputStream in) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len=in.read(buffer)) >0) {
out.write(buffer, 0, len);
}
out.flush();
return out;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/*public static void main(String[] args) {
deleteDir("C:\\Users\\mh\\Desktop\\TEMP");
}*/
}
测试结果:
SpringBoot+POI报表批量导出的更多相关文章
- 多表批量导出txt及打压缩包下载
在一些特殊的业务系统中,有些客户查看报表数据时不需要在浏览器上逐一查看,需要在页面端选择要查看的报表名称(可多选),选择条件,然后将所选中的报表批量导出到txt文件中并且要把批量导出的结果文件打 ...
- Java使用POI实现数据导出excel报表
Java使用POI实现数据导出excel报表 在上篇文章中,我们简单介绍了java读取word,excel和pdf文档内容 ,但在实际开发中,我们用到最多的是把数据库中数据导出excel报表形式.不仅 ...
- java操作Excel之POI(5)利用POI实现使用模板批量导出数据
后台导出方法: 在源文件夹src下面放个准备好的模板:/com/cy/template/userExportTemplate.xls,这个模板有头部一行: /** * 后台导出方法 * 利用POI实现 ...
- java操作Excel之POI(4)利用POI实现数据的批量导出
后台导出方法: /** * 后台导出方法 * 利用POI实现数据的批量导出 */ public String export() throws Exception{ Connection con = n ...
- java使用POI操作excel文件,实现批量导出,和导入
一.POI的定义 JAVA中操作Excel的有两种比较主流的工具包: JXL 和 POI .jxl 只能操作Excel 95, 97, 2000也即以.xls为后缀的excel.而poi可以操作Exc ...
- POI操作Excel(批量导出数据/下载excel)
目录 1.第一个demo:创建工作簿,创建sheet页,创建单元格 2.创建一个时间格式的单元格 3.遍历工作簿的行和列并获取单元格内容 4.文本提取 5.单元格对齐方式 ...
- Java中使用poi导入、导出Excel
一.介绍 当前B/S模式已成为应用开发的主流,而在企业办公系统中,常常有客户这样子要求:你要把我们的报表直接用Excel打开(电信系统.银行系统).或者是:我们已经习惯用Excel打印.这样在我们实际 ...
- POI报表打印
一.Excel报表(POI) 1.需求说明 在企业级应用开发中,Excel报表是一种最常见的报表需求.Excel报表开发一般分为两种形式: 1.为了方便操作,基于Excel的报表批量上传数据 2.通过 ...
- 使用VUE+SpringBoot+EasyExcel 整合导入导出数据
使用VUE+SpringBoot+EasyExcel 整合导入导出数据 创建一个普通的maven项目即可 项目目录结构 1 前端 存放在resources/static 下 index.html &l ...
随机推荐
- Curl实现ElasticSearch的增删改查
一.添加数据(laravel必须安装Curl扩展) $data = [ 'username'=>"张三", 'sex'=>"女", 'age'=&g ...
- git连接不上远程仓库---visualstudio提交代码报错:no upstream configured for branch 'master'
1,新建文件夹,在文件下下鼠标右键git bush--->git init,初始化仓库: 2,设置gitthub仓库地址:git remote add origin https://github ...
- Linux中安装tomcat后,window中访问不到tomcat的欢迎界面问题
首先,可以通过xftp把下载的tomcat的tar.gz包传输到Linux中. 然后进行解压,tar -zxvf tomcat的压缩包名称(可以使用tab键快速补齐) 解压后,可以使用修改/con ...
- lldb调试mysql 插件命令
# attach process llvm process attach --pid 64924 # 添加断点 breakpoint set -n dispatch_command(enum_ ...
- 小程序一个大盒子里面的盒子内容居中对其显示wxss写法
对小程序研究感兴趣的可加(交流QQ群:604788754)入群联系群主可得到小程序教学资源. 这个案例只是想展示效果,内容部分未进行for循环绑定处理: WXML: <view class=&q ...
- CentOS 7 常用命令大全
CentOS7 常用命令集合 这两天一直在对CentOS 7.2进行初体验,各种学习命令肿么用,不过其实大多和DOS是一样的,只是命令的表达上可能有点儿不一样,毕竟这些都不是一家出来的嘛~ 废话不多说 ...
- Java实现post和get请求
GET请求:GET请求会向服务器发索取数据的请求,从而来获取信息,该请求就像数据库的select操作一样,只是用来查询一下数据,不会修改.增加数据,不会影响资源的内容,即该请求不会产生副作用.无论进行 ...
- Forth 文本解释程序
body, table{font-family: 微软雅黑; font-size: 13.5pt} table{border-collapse: collapse; border: solid gra ...
- 浅谈Object.assign()
Object.assign()方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象.返回值为目标对象. 1 Object.assign 是 ES6 新添加的接口,主要的用途是用来合并多个 Ja ...
- csla框架__使用Factory方式实现Csla.BusinessBase对象数据处理
环境:.net4.6+csla4.6 实现:对象的数据库访问及数据库执行使用Factory方式进行封闭. 正文: 以前在使用csla框架完成业务对象的定义时所有的数据处理都在对象内部实现,也不能说不好 ...