最近项目中有这样的需求:就是选择页面上的多条记录,每一条记录生成一个excel,然后把所有选择记录生成的excel打包成zip包供用户下载。
后台代码:
/**
* 批量导出Excel
* @return
* @throws DBException
*/
@SuppressWarnings("unchecked")
public String batchExport() throws DBException{
@SuppressWarnings("unused")
List<String> chkList = this.checkValueToList();//获取复选框的值
List<File> srcfile=new ArrayList<File>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHSS");
String path = sdf.format(new Date());
String serverPath = request.getSession().getServletContext().getRealPath("/");
//在服务器端创建文件夹
File file = new File(serverPath+path);
if(!file.exists()){
file.mkdir();
}
for (int i = 0; i < chkList.size(); i++ ){
String t[] = chkList.get(i).split("\\|");
LhjcOrgSelfQuery lhjcunioncheckquery = new LhjcOrgSelfQuery();
lhjcunioncheckquery.setChnoticeId(t[0]);
lhjcunioncheckquery.setOrgId(t[1]);
lhjcunioncheckquery.setSelfChTempId(t[2]);
List<Map<String,String>> reportViews=commonService.getObjectPages("ExportLhjcunioncheckresultReportView", lhjcunioncheckquery);
String orgName = (String)commonService.get2Object("getUnioncheckOrgName", t[1]);
//生成excel的名字
String templateName = nyear+"深圳市党政机关信息安全检查结果-"+(orgName==null?"未知单位":orgName);
/** 表头数组 */
String[] headArray = new String[]{"编码","检查项名称"," 检查内容 ","考核类型"," 检查结果 "," 备注 ","权重","得分"};
/** 字段名数组 */
String[] fieldArray = new String[]{"CHECKITEMCODE","CHITEMNAME","CHCONTENT","REPORTTYPE","QUESTDESC","CHITEMDESC","REPORTWEIGHT","UNIONSCORE"};
ExportUtils exportUtils = new ExportUtils();
exportUtils.setTitle(templateName);
exportUtils.setHead(templateName);
exportUtils.setHeadArray(headArray);
exportUtils.setFieldArray(fieldArray);
try {
HttpServletResponse response = ServletActionContext.getResponse();
SimpleDateFormat sfm = new SimpleDateFormat("yyyy-MM-dd");
String filename = templateName + "_" + sfm.format(new Date());
String encodedfileName = new String(filename.getBytes(), "GBK");
//将生成的多个excel放到服务器的指定的文件夹中
FileOutputStream out = new FileOutputStream(serverPath+path+"\\"+encodedfileName+".xls");
if(fileType.indexOf(",") != -1){
fileType = StringUtils.substringBefore(fileType, ",");
}
response.setHeader("Content-Disposition", " filename=\"" + encodedfileName + "." + fileType + "\"");
//导出excel
if ("xls".equals(fileType) || "xlsx".equals(fileType)) {
exportUtils.exportExcel(reportViews,fileType,out);
} else if("doc".equals(fileType) || "docx".equals(fileType)){
exportUtils.exportWord(reportViews, fileType, out);
} else if("pdf".equals(fileType)){
exportUtils.exportPdf(reportViews, out);
}
srcfile.add(new File(serverPath+path+"\\"+encodedfileName+".xls"));
} catch (Exception e) {
e.printStackTrace();
}
}
//将服务器上存放Excel的文件夹打成zip包
File zipfile = new File(serverPath+path+".zip");
this.zipFiles(srcfile, zipfile);
//弹出下载框供用户下载
this.downFile(ServletActionContext.getResponse(),serverPath, path+".zip");
return null;
}
/**
* 将多个Excel打包成zip文件
* @param srcfile
* @param zipfile
*/
public 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();
}
}
public void downFile(HttpServletResponse response,String serverPath, String str) {
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/x-download");// 设置response内容的类型
response.setHeader(
"Content-disposition",
"attachment;filename="
+ URLEncoder.encode(str, "GBK"));// 设置头部信息
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();
}
}
页面调用:
<script language="javascript">
<!--
//批量导出Excel
function batchExport(){
var chkbox = $("input[type='checkbox'][name='chk'][checked]");
if(chkbox.length == 0){
alert('请选择一条或多条记录操作!');
return;
}
$("#exportLoading").html('<img src="${ctx}/images/loading.gif"/>');
var checkboxvalue = '';
chkbox.each(function(){
checkboxvalue += $(this).val()+",";
});
var nyear = document.getElementById('nyear').value;
if(checkboxvalue != null && checkboxvalue.length > 0){
checkboxvalue = checkboxvalue.substring(0,checkboxvalue.length-1);
$('#checkboxvalue').val(checkboxvalue);
var form = document.forms[0];
form.action="${ctx}/core/lhjc/lhjccheckjd/batchExport.action?fileType=xls&chvalue="+checkboxvalue+"&nyear="+nyear;
form.submit();
$("#exportLoading").empty();
}
}
-->
</script>
分享到:
相关推荐
java中将多个excel打包成zip文件下载.rar
30万的数据量,生成多个excel最后打包成zip下载,是工程,直接导入就行
生成excel并打包成zip文件,包含主要的生成类和如何打包的代码,主要是嵌套的关系
包含了使用的jar包,以及一个Java类,实现了使用Java对多目录多层级的文件进行打包,以及对ZIP包进行解压缩的操作。
直接可以用的项目。数据量大,导出多个excel然后压缩成zip文件。。。
主要为大家详细介绍了java后台批量下载文件并压缩成zip下载的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
Java根据Url把多个文件下载到指定的文件夹目录,然后再将文件夹目录打包成zip导出,包括子目录也可以打包,有个简单的导出html页面,点击导出按钮下载zip。
poi.zip java读取excel文件,其中bin压缩文件中含有jar包,eclipse导入时可直接使用;src压缩文件含有java源代码,需要阅读源码的童鞋可以下载使用
目前项目有一个需求“数据的离线导入导出”,需要将数据分模块导入到不同的excel,然后压缩成数据包下载
本资源是用java代码将文件夹打成zip包,网上打zip包的代码会出现中文乱码和含空文件出现问题。本资源解决了这些问题,还加入一些合理化设计。 经过测试,基本没有问题。此资源比较适合项目使用。
java 生成zip压缩文件 java 生成zip压缩文件
jquery把图片文件打包成ZIP文件提供下载,不用再后台生成储存
java 实现指定目录下的文件打包zip格式 并指定存放zip包
分步生成csv,获取数据第一行生成文件标题,同时生成第一行数据,返回标题名称。 将多csv文件压缩成zip,之后删除原csv文件
java生成PDFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
应用java来压缩需要打包的文件,在系统管理中将毛哥路径或者某个文件夹压缩成zip包
/** * 根据 策划的配置表来生成 json * excel 目前使用的版本为2007,其他版本未测试... * 读取文件 一般用于本地文件的生成, * 二进制的方式,一般用于 后台管理界面 的文件上传后的处理。 * @author wgq * */
Java把文件压缩成zip,粘贴在项目中即可使用
用Java语言采用接口设计模式、代理设计模式、工厂设计模式实现对excel中的表实现基本的...使用Java内置的poi jar包实现excel的操作,使用工厂模式、DAO设计模式等,思想很简单,可供设计模式参考,包括代码+文档+jar包