简单介绍下我实现的功能,首先是我的excel上传,它是以blob字段存储在oracel数据库中的,我实现的是循环遍历blob字段并使用io流进行打包下载,如有需要可自行修改

使用技术有,springMVC,mabits , bootstrap

1.前台

这里给出主要代码块

<div class="row">
<div class="col-md-12 ">
<a href="tab-trainer-info.htm?status=1" class="btn btn-danger" title='#springMessage("back")'> <i class="glyphicon glyphicon-step-backward"></i></a> <a href="downloadPreHomeWorkZIP.htm?sessionId=$!sessionId" class="btn btn-info downloadPreZip" title='#springMessage("preWorkZip")'> <i class="glyphicon glyphicon-download-alt"></i> #springMessage("preWorkZip")</a> <a href="downloadAfterHomeWorkZIP.htm?sessionId=$!sessionId" class="btn btn-info downloadAfterZip" title='#springMessage("afterWorkZip")'> <i class="glyphicon glyphicon-download-alt"></i> #springMessage("afterWorkZip")</a>
</div>
</div>

注意这里点击按钮时用的超链接,不要用的ajax提交,ajax慎用,我自己一开始使用的ajax,最后无法下载,搞了半天,后来百度,说ajax下载无法调用浏览器的下载机制,如果有必要也可以使用(要用form封装,我这里不再具体介绍,有尝试的小伙伴,可以共享一下,哈哈)

2. Controller  读取数据

@RequestMapping(value = "downloadPreHomeWorkZIP")
public void downloadLetterZIP(trainTraineeWorkModel query, HttpServletResponse response, HttpServletRequest request)
throws IOException, SQLException {
String serverPath = request.getSession().getServletContext().getRealPath("/") + "\\upload\\tempExcel"; //设置下载excel的临时文件夹
List<File> srcfile = new ArrayList<File>(); //声明一个集合,用来存放多个Excel文件路径及名称
// 得到路径下的文件,如果不存在创建文件夹
File file = new File(serverPath);
if (!file.exists()) {
file.mkdir();
}
List<Map> employees = employeeService // 查询学员上传的课前课后作业 (这里根据自己的需要获取数据,写入流中)
.getMapTraineesBySessionId(query.getSessionId());
if (employees.size() != 0) {
for (Map map : employees) {
BLOB blob = (BLOB) map.get("BEFORECLASS_WORK");
if (blob != null && blob.length() != 0) {
String employeeCode = (String) map.get("EMPLOYEE_CODE");
String filename = employeeCode + "_" + DateUtil.getExportDate(); //定义现在excel文件名称,注意这里不是压缩包的名称
ZipUtils.execute(serverPath +"\\"+ filename+ ".xls", blob); //ZipUtils是我自己定义的一个工具类,因为用到的下载太多了,往下看
String encodedfileName = new String(filename.getBytes(), "UTF-8");
srcfile.add(new File(serverPath + "\\" + encodedfileName + ".xls")); //存放到List集合中
}
}
// 将服务器上存放Excel的文件夹打成zip包
File zipfile = new File(serverPath+"\\" + "PreWork" + ".zip");
ZipUtils.zipFiles(srcfile, zipfile);// 实现将多个excel打包成zip文件
//下载
ZipUtils.downFile(response, serverPath, "PreWork" + ".zip"); //实现将压缩包写入流中,下载到本地,并删除临时文件中的压缩包及文件 }
}

3.使用工具类

这里是我第二步说的自己定义的工具类,我用的maven,需要导入一些Io流包

package common.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
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.net.URLEncoder;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; import javax.servlet.http.HttpServletResponse; import oracle.sql.BLOB; public class ZipUtils {
/**
* 将多个Excel打包成zip文件
* @param srcfile
* @param zipfile
*/
public static void zipFiles(List<File> srcfile, File zipfile) {
byte[] buf = new byte[1024];
try {
// Create the ZIP file
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
// Compress the files
for (int i = 0; i < srcfile.size(); i++) {
File file = srcfile.get(i);
FileInputStream in = new FileInputStream(file);
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(file.getName()));
// Transfer bytes from the file to the ZIP file
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// Complete the entry
out.closeEntry();
in.close();
}
// Complete the ZIP file
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//filename为单个excel的路径和excel的名称,blob就是获取的blob数据
public static int execute(String filename, BLOB blob)
{
int success = 1;
try
{
File blobFile = new File(filename);
FileOutputStream outStream = new FileOutputStream(blobFile);
InputStream inStream = blob.getBinaryStream();
int length = -1;
int size = blob.getBufferSize();
byte[] buffer = new byte[size];
while ((length = inStream.read(buffer)) != -1)
{
outStream.write(buffer, 0, length);
outStream.flush();
}
inStream.close();
outStream.close();
}
catch (Exception e)
{
e.printStackTrace();
success = 0;
}
finally
{
return success;
} } /**
* 删除目录下所有的文件;
* @param path
*/
public static boolean deleteExcelPath(File file){
String[] files = null;
if(file != null){
files = file.list();
} if(file.isDirectory()){
for(int i =0;i<files.length;i++){
boolean bol = deleteExcelPath(new File(file,files[i]));
if(bol){
System.out.println("删除成功!");
}else{
System.out.println("删除失败!");
}
}
}
return file.delete();
} public static void downFile(HttpServletResponse response,String serverPath, String str) {
//下面注释代码虽然少,但是慎用,如果使用,压缩包能下载,但是下载之后临时文件夹会被锁住被jvm占用,不能删除
// response.setCharacterEncoding("utf-8");
// try {
// File file=new File(serverPath,str);
// response.setHeader("Content-Disposition",
// "attachment; filename="+ StringUtil.encodingFileName(str));
// response.setContentType("application/octet-stream; charset=utf-8");
// InputStream in1 =new FileInputStream(file.getPath());
// IOUtils.copy(in1, response.getOutputStream());
//
// }
// catch (IOException ex) {
// ex.printStackTrace();
// } try {
String path = serverPath +"\\"+ str;
File file = new File(path);
if (file.exists()) {
InputStream ins = new FileInputStream(path);
BufferedInputStream bins = new BufferedInputStream(ins);// 放到缓冲流里面
OutputStream outs = response.getOutputStream();// 获取文件输出IO流
BufferedOutputStream bouts = new BufferedOutputStream(outs);
response.setContentType("application/ostet-stream");// 设置response内容的类型
response.setHeader(
"Content-disposition",
"attachment;filename="
+ URLEncoder.encode(str, "UTF-8"));// 设置头部信息
int bytesRead = 0;
byte[] buffer = new byte[8192];
//开始向网络传输文件流
while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
bouts.write(buffer, 0, bytesRead);
}
bouts.flush();// 这里一定要调用flush()方法
ins.close();
bins.close();
outs.close();
bouts.close();
} else {
response.sendRedirect("../error.jsp");
}
} catch (IOException e) {
e.printStackTrace();
}finally{
File file1=new File(serverPath);
deleteExcelPath(file1); //删除临时目录
}
}
}

java 压缩导出多个excel的更多相关文章

  1. java代码导出数据到Excel、js导出数据到Excel(三)

     jsp内容忽略,仅写个出发按钮:          <button style="width: 100px" onclick="expertExcel()&quo ...

  2. java Servlet导出数据到Excel文件

    package com.lbc.excel.servlet; import java.io.IOException; import java.util.ArrayList; import java.u ...

  3. 在Java中导出word、excel格式文件时JSP页面头的设置

    我们在JSP中往往会把一些表格里的东西需要导出到本地,一般都是导成word.excel格式的文件.这只需要在JSP页面头设置及在<head></head>标签中添加下面的代码: ...

  4. Java中导出到Excel实现_aspose.cells

    参考http://183615215-qq-com.iteye.com/blog/1858208 包下载:http://pan.baidu.com/s/1o6ju0ZK,将lib的jar包导入到工程中 ...

  5. 重构:以Java POI 导出EXCEL为例

    重构 开头先抛出几个问题吧,这几个问题也是<重构:改善既有代码的设计>这本书第2章的问题. 什么是重构? 为什么要重构? 什么时候要重构? 接下来就从这几个问题出发,通过这几个问题来系统的 ...

  6. java压缩文件或文件夹并导出

    java压缩文件或文件夹并导出 tozipUtil: package com.zhl.push.Utils; import java.io.File; import java.io.FileInput ...

  7. 【转载】Java导入导出excel

    转自:https://blog.csdn.net/jerehedu/article/details/45195359 目前,比较常用的实现Java导入.导出Excel的技术有两种Jakarta POI ...

  8. Java 使用stringTemplate导出大批量数据excel(百万级)

    目前java框架中能够生成excel文件的的确不少,但是,能够生成大数据量的excel框架,我倒是没发现,一般数据量大了都会出现内存溢出,所以,生成大数据量的excel文件要返璞归真,用java的基础 ...

  9. Java 导出大批量数据excel(百万级)(转载)

    参考资料:http://bbs.51cto.com/thread-1074293-1-1.html                 http://bbs.51cto.com/viewthread.ph ...

随机推荐

  1. ubuntu中安装ftp服务器

    1. 实验环境 ubuntu14.04 2.vsftpd介绍 vsftpd 是“very secure FTP daemon”的缩写,是一款在Linux发行版中最受推崇的FTP服务器程序,安全性是它的 ...

  2. java web 学习总结之 Servlet/JSP 编码问题

    Servlet和JSP编码问题 字节流: 1.得到OutputStream  字节流 OutputStream os = response.getOutputStream();   用默认编码输出数据 ...

  3. PDO浅谈之php连接mysql

    一.首先我们先说一下什么是pdo?  百科上说 PDO扩展为PHP访问数据库定义了一个轻量级的.一致性的接口,它提供了一个数据访问抽象层,这样,无论使用什么数据库,都可以通过一致的函数执行查询和获取数 ...

  4. 图片与字符串(base64编码)的转化

    package com.demo; import java.util.*; import java.io.*; import sun.misc.BASE64Decoder; import sun.mi ...

  5. ASP.NET Core 处理 404 Not Found

    问题 在没有修改任何配置的情况下,这是用户使用 Chrome 访问不存在的URL时会看到的内容: 幸运的是,处理错误状态代码非常简单,我们将在下面介绍三种技术. 解决方案 在以前的ASP.NET MV ...

  6. kubeernetes节点资源限制

    实际应用中发现,部分节点性能不足,某些较大的服务如果跑在这些机器上.会很快消耗该机器的内存和cpu资源,如果用uptime看一下的就会发现负载特别高(合理的范围这个值应该等于cpu个数),高到一定值就 ...

  7. 阿里巴巴Java规约插件试用

    阿里Java开发规约Eclipse插件介绍 阿里巴巴集团配合<阿里巴巴Java开发手册>PDF终极版开发的IDE插件,目前包括IDEA插件.Eclipse插件. 安装 检查环境 插件要求: ...

  8. ASP.NET MVC5+EF6+EasyUI 后台管理系统(87)-MVC Excel导入和导出

    本文示例代码下载: 链接:http://pan.baidu.com/s/1jHBdgCA 密码:hzh7 ps:Vs数据库脚本在解压目录下,修改web.config数据库链接,示例代码包含:导入,导出 ...

  9. win10 uwp 按下等待按钮

    我们经常需要一个按钮,在按下时,后台执行Task,这时不能再次按下按钮. 我们使用自定义控件,首先新建一个类,我把它命名是ProgressButton 一个进度条按钮,也就是我们按下时发生进度条,完成 ...

  10. FixedUpdate真的是固定的时间间隔执行吗?聊聊游戏定时器

    0x00 前言 有时候即便是官方的文档手册也会让人产生误解,比如本文将要讨论的Unity引擎中的FixedUpdate方法. This function is called every fixed f ...