我的导出excel,如果文件过多生成多个excel的压缩包的功能
Controller代码:
@ResponseBody @RequestMapping(value = "/export") public Object doExport(HttpServletResponse response, @ModelAttribute("settleAccountsForm")ChannelSettleAccountsManagerForm settleAccountsForm){ Map<String,Object> resultMap = new HashMap<>(); ChannelSettleAccountsManagerBo settleAccountBo = new ChannelSettleAccountsManagerBo(); try { BeanUtils.copyProperties(settleAccountBo, settleAccountsForm); } catch (Exception e) { logger.error("属性复制转换失败,查询条件使用空,{}",e); e.printStackTrace(); } settleAccountBo.setPageSize(6000); settleAccountBo.setPageCurrent(1); int itemCount = settleAccountsManagerService.getItemsCountByBo(settleAccountBo); List<ChannelSettleAccountsManagerVo> vos = null; if(itemCount <= EXCEL_SIZE){ try { vos = settleAccountsManagerService.queryListByBo(settleAccountBo); if(vos.size() == 0){ vos.add(new ChannelSettleAccountsManagerVo()); } ExcelUtil<ChannelSettleAccountsManagerVo> excelUtil = new ExcelUtil<>("渠道结算管理"); excelUtil.export(vos); excelUtil.flushToRequest(response, "channelSettleAccountsMessage"); resultMap.put("statusCode","200"); resultMap.put("message","导出成功!"); } catch (Exception e) { logger.info("导出文件失败!{}",e); e.printStackTrace(); resultMap.put("statusCode","300"); resultMap.put("message","导出失败!"); } }else{ File settleAccountsDir = new File("渠道结算管理"); settleAccountsDir.mkdirs(); for(int i = 0; i < itemCount; i = i + EXCEL_SIZE){ vos = settleAccountsManagerService.queryListByBo(settleAccountBo); ExcelUtil<ChannelSettleAccountsManagerVo> excelUtil = new ExcelUtil<>("渠道结算管理"); try{ excelUtil.export(vos); File file = new File(settleAccountsDir, "channelSettleAccounts_" + i + ".xls"); excelUtil.exportStream(new FileOutputStream(file)); } catch (Exception e) { logger.error("导出excel失败,{}", e); e.printStackTrace(); resultMap.put("statusCode","300"); resultMap.put("message","导出失败!"); return resultMap; } } //将文件夹变成压缩文件 String zipName = "渠道结算管理.zip"; try{ zipName=new String(zipName.getBytes("gb2312"),"iso8859-1"); }catch(Exception ex){ ex.printStackTrace(); } response.setContentType("APPLICATION/OCTET-STREAM"); response.setHeader("Content-Disposition","attachment; filename="+zipName); File zipFile = null; FileInputStream input = null; try{ zipFile = new File(zipName); ZipUtils.doCompress(settleAccountsDir, zipFile); input = new FileInputStream(zipFile); IOUtils.copy(input, response.getOutputStream()); resultMap.put("statusCode","200"); resultMap.put("message","导出成功!"); } catch (Exception e) { e.printStackTrace(); logger.error("导出失败,错误{}", e); resultMap.put("statusCode","300"); resultMap.put("message","导出失败!"); } finally { try { input.close(); } catch (IOException e) { e.printStackTrace(); } FileUtils.deleteFolder(settleAccountsDir); zipFile.delete(); } } return resultMap; }
我想这应该就够了。
补充下ExcelUtil吧,下次如果需要的话可以使用:
package com.allcheer.acl.omc.util; import com.allcheer.acl.omc.util.enums.ExcelElement; import com.allcheer.acl.omc.util.enums.ExcelFormat; import com.allcheer.acl.omc.util.enums.ExcelSelect; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.lang3.time.DateFormatUtils; import org.apache.poi.hssf.usermodel.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletResponse; import java.io.OutputStream; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.*; public class ExcelUtil<T> { Logger logger = LoggerFactory.getLogger(ExcelUtil.class); public HSSFWorkbook wb; String sheet; HSSFCellStyle styleBody; boolean fieldsNotSup = false; public ExcelUtil() { wb = new HSSFWorkbook(); sheet = "sheet1"; initStyle(wb); } public ExcelUtil(String sheetName) { this(); if (sheetName != null) { sheet = sheetName; } } public void initStyle(HSSFWorkbook wb) { styleBody = wb.createCellStyle(); styleBody.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直 styleBody.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平 styleBody.setWrapText(true); // 设置是否能够换行,能够换行为true } public void export(List<T> ts) throws Exception { if (ts == null) { throw new Exception("export Excel error, data is null"); } CollectionUtil<T> cu = new CollectionUtil<T>(); List<List<T>> divideIntoGroups = cu.divideIntoGroups(ts, 65535); int index = 1; HSSFSheet createSheet; for (List<T> list : divideIntoGroups) { createSheet = wb.createSheet(sheet + index++); exportSheet(list, createSheet); } } private void exportSheet(List<T> list, HSSFSheet createSheet) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { T t = null; HSSFRow row = null; String[] beanFieldNames = null; Map<String, String> excelFieldMap = null; int rowIndex = 1; for (int i = 1; i <= list.size(); i++) { t = list.get(i - 1); if (t == null) { continue; } if (beanFieldNames == null || excelFieldMap == null) { excelFieldMap = getExcelFieldMap(t); beanFieldNames = (String[]) excelFieldMap.keySet().toArray(new String[excelFieldMap.keySet().size()]); } if (rowIndex == 1) { HSSFRow oneRow = createSheet.createRow(0); exportRow(oneRow, beanFieldNames, excelFieldMap); } row = createSheet.createRow(rowIndex++); exportRow(t, row, beanFieldNames); } } private void exportRow(HSSFRow row, String[] beanFieldNames, Map<String, String> excelFieldMap) { HSSFCell cell = null; for (int i = 0; i < beanFieldNames.length; i++) { cell = row.createCell(i); cell.setCellValue(excelFieldMap.get(beanFieldNames[i])); } } private void exportRow(T t, HSSFRow row, String[] beanFieldNames) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { String beanFieldName = null; String value = null; HSSFCell cell = null; for (int j = 0; j < beanFieldNames.length; j++) { beanFieldName = beanFieldNames[j]; value = fomcatValue(t, beanFieldName); cell = row.createCell(j); cell.setCellValue(value); cell.setCellStyle(styleBody); } } private String fomcatValue(T t, String beanFieldName) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { String value = BeanUtils.getSimpleProperty(t, beanFieldName); try { Field field = t.getClass().getDeclaredField(beanFieldName); boolean annotationPresent = field.isAnnotationPresent(ExcelFormat.class); if(annotationPresent){ ExcelFormat annotation = field.getAnnotation(ExcelFormat.class); String dateFormat = annotation.dateFormat(); if(dateFormat!= null && !"".equals(dateFormat)){ value = DateFormatUtils.format(new Date(value), dateFormat); } } boolean annotationPresent2 = field.isAnnotationPresent(ExcelSelect.class); if(annotationPresent2){ ExcelSelect annotation = field.getAnnotation(ExcelSelect.class); String[] select = annotation.select(); if(select!= null && (select.length % 2 == 0)){ for(int i = 0 ; i<select.length ; i=i+2){ if(select[i] != null && select[i].equals(value)){ value = select[i+1]; } } } } } catch (Exception e) { logger.error("数据格式化异常,使用原数据",e); } return value; } public void flushToRequest(HttpServletResponse response, String fileName) throws Exception { if (fileName == null) { fileName = "default"; } try { response.setContentType("application/vnd.ms-excel"); // response.setHeader("Content-disposition", String.format("attachment;filename=%s.xls", fileName)); fileName=new String(fileName.getBytes("gb2312"),"iso8859-1"); response.setHeader("Content-disposition", String.format("attachment;filename=%s.xls", fileName)); OutputStream ouputStream = response.getOutputStream(); exportStream(ouputStream); } catch (Exception e) { logger.error("导出excel错误:", e); throw e; } } public void exportStream(OutputStream o) throws Exception { try { wb.write(o); o.flush(); o.close(); } catch (Exception e) { logger.error("导出excel错误:", e); throw e; } } public Map<String, String> getExcelFieldMap(T t) { Map<String, String> map = new HashMap<String, String>(); Map<String, String> ret = new LinkedHashMap<String, String>(); Map<Integer, String> order = new HashMap<Integer, String>(); Field[] fields = t.getClass().getFields(); if (fieldsNotSup) { fields = null; } Field[] thisFields = t.getClass().getDeclaredFields(); fields = Union(fields, thisFields); boolean annotationPresent; for (Field f : fields) { if (f == null) { continue; } annotationPresent = f.isAnnotationPresent(ExcelElement.class);// 判断是否有该类型的注解 if (annotationPresent) { ExcelElement test = f.getAnnotation(ExcelElement.class);// 得到该类型的注解 map.put(f.getName(), test.field()); order.put(test.index(), f.getName()); } } // 排序 Set<Integer> keySet = order.keySet(); Integer[] array = keySet.toArray(new Integer[keySet.size()]); Arrays.sort(array); for (int i = 0; i < array.length; i++) { String fieldName = order.get(array[i]); String excelFieldName = map.get(fieldName); ret.put(fieldName, excelFieldName); } return ret; } public Field[] Union(Field[] field1, Field[] field2) { Field[] all = null; if (field1 != null && field2 != null) { all = new Field[field2.length + field1.length]; System.arraycopy(field1, 0, all, 0, field1.length); System.arraycopy(field2, 0, all, field1.length, field2.length); } else if (field1 == null && field2 != null) { all = field2; } else if (field1 != null && field2 == null) { all = field1; } return all; } /** * 是否导出父类的字段: true 不导 false 导 * * @param b */ public void fieldsNotSuperClass(boolean b) { fieldsNotSup = b; } }
压缩工具类,这个是我百度上找的,我没看过压缩有关类的文档:
package com.allcheer.acl.omc.util; /** * Created by zhen on 2017-06-12. */ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * 压缩文件工具类 */ public class ZipUtils { public static void doCompress(String srcFile, String zipFile) throws Exception { doCompress(new File(srcFile), new File(zipFile)); } /** * 文件压缩 * @param srcFile 目录或者单个文件 * @param destFile 压缩后的ZIP文件 */ public static void doCompress(File srcFile, File destFile) throws Exception { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(destFile)); if(srcFile.isDirectory()){ File[] files = srcFile.listFiles(); for(File file : files){ doCompress(file, out); } }else { doCompress(srcFile, out); } out.close(); } public static void doCompress(String pathname, ZipOutputStream out) throws IOException{ doCompress(new File(pathname), out); } public static void doCompress(File file, ZipOutputStream out) throws IOException{ if( file.exists() ){ byte[] buffer = new byte[1024]; FileInputStream fis = new FileInputStream(file); out.putNextEntry(new ZipEntry(file.getName())); int len = 0 ; // 读取文件的内容,打包到zip文件 while ((len = fis.read(buffer)) > 0) { out.write(buffer, 0, len); } out.flush(); out.closeEntry(); fis.close(); } } }

浙公网安备 33010602011771号