java 动态生成多个excel文件打成zip包供用户下载

最近项目中有这样的需求:就是选择页面上的多条记录,每一条记录生成一个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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值