excel打包成zip提供用户下载 要用到ant.jar ant.jar下载地址
/**
* zip下载 @author yzh
* @return
* @throws Exception
*/
public String downzip() throws Exception {
this.checkYM();
Common c = new Common();
HttpServletResponse response = ServletActionContext.getResponse();
List<Company> companyList = new ArrayList<Company>();//公司列表
Company company = (Company) session.get("company");// 取得当前用户的公司对象
if (company.getMonadmin().equals(1)) {// 如果用户所属的公司为管理公司
companyList = this.unitService.findMonCompany();// 取得所有受管理的公司列表
if (this.companyid == null) {// 页面请求的公司id如果为空,则查询当前用户所属公司
this.companyid = companyList.get(0).getUnitid();
}
}
if(!companyList.isEmpty()){
List<String> namelist = new ArrayList<String>();
List<byte[]> bytelist = new ArrayList<byte[]>();
for (Company company1 : companyList) {
List<Object> list = getCollectExcelBytes(company1);//取得byte[]数据与文件名称的方法
String basename = (String) list.get(0);
byte[] buf = (byte[]) list.get(1);
namelist.add(basename);
bytelist.add(buf);
}
String filename = "所有公司_合同额及收款情况"+ "_" + year
+ "年" + month + "月_" + c.getStrDate();
getZip(filename,namelist,bytelist,response);//zip打包处理的方法
}
return null;
}
/**
* @author yzh
* 取得 合同及收款报表 byte[]数组及文件名称
*/
private List<Object> getCollectExcelBytes(Company company) throws Exception {
List<Object> list = new ArrayList<Object>();
this.checkYM();//年月验证类,略
Common c = new Common();//时间处理类,略
String filename = "合同额及收款情况_" + company.getNameshort() + "_" + year
+ "年" + month + "月_" + c.getStrDate()+".xls";
ByteArrayOutputStream os = new ByteArrayOutputStream();// 取得输出流
WritableWorkbook wbook = collectService.exportCollectExcel(
company.getUnitid(), this.year, this.month, os);//取得excel 对象方法,略
wbook.write(); // 写入文件
wbook.close();
list.add(filename);
list.add(os.toByteArray());
return list;
}
/**
* @author yzh 取得动态取得zip文件
* @param filename zip文件初始名
* @param list 要打包文件名集合
* @param tytess 要打包文件byte[]数组集合
* @param response HttpServletResponse
* @throws Exception
*/
public void getZip(String filename,List<String> list,List<byte[]> tytess,HttpServletResponse response)
throws Exception {
byte[] buffer = new byte[1024];
filename = new String(filename.getBytes(),"iso8859-1");
// 清空response
response.reset();
// 设置response的Header
response.setHeader("Content-disposition", "attachment; filename="
+ filename + ".zip");// 设定输出文件头
/*使用ant.jar中的org.apache.tools.zip.*; 不要使用java.util.zip.*;
避免中文乱码问题 主要原因是因为java.util.zip使用编码和WinZip和WinRar使用的不同,
解压后,使用java.util.zip.*有中文的话会出现乱码 */
ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
for (int j = 0; j < list.size(); j++) {
String name = list.get(j);
byte[] bytes = tytess.get(j);
if(name!=null && bytes!=null){//非空
InputStream fis = new ByteArrayInputStream(bytes);
out.putNextEntry(new ZipEntry(name.toString()));
int len;
while ((len = fis.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.flush();
out.closeEntry();
fis.close();
}
}
out.flush();
out.close();
}