使用HSSFWorkbook 模式
主要方便是模板後能夠動態添加類。
對於大量數據 處理速度慢+內存消耗比較大。建議使用SXSSFWorkbook
public class OfflineNonCityEventListener implements ApplicationListener<OfflineNonCityEvent> {
private static final Logger logger = LoggerFactory.getLogger(OfflineNonCityEventListener.class);
@Autowired
private ReportRecordsService reportRecordsService;
@Autowired
private ReportExcutLogService reportExcutLogService;
@Autowired
private JdbcTemplate jdbcTemplate;
@Value("${report.file.baseDir}")
private String baseFilePath;
@Value("${report.file.baseDir.win}")
private String baseFilePath_win;
@Value("${report.details.pageSize}")
private Integer pageSize;
//listener實現
public void onApplicationEvent(OfflineNonCityEvent event) {
Long issuerId=event.getIssuerId();
Issuer issuer=event.getIssuer();
String beginTime=event.getBeginTime();
String endTime=event.getEndTime();
String loginfo="";
Integer reportRecordsId=event.getReportRecordsId();
if (issuerId == null || beginTime == null || endTime == null) {
return;
}
ReportRecords reportRecords =reportRecordsService.geReportRecordsById(reportRecordsId);
reportRecordsService.markStartTime(reportRecordsId);
Workbook wb = null;
boolean hasData = false;
StringBuffer sbf=new StringBuffer();
if(System.getProperty("os.name").toLowerCase().startsWith("win")){
baseFilePath=baseFilePath_win;
}
try {
File template = ResourceUtils.getFile("classpath:templates/ibms-offlineNonCity-details.xlsx");
wb = POIUtils.createWorkBook(template);
String fileDirectory = baseFilePath + File.separator + reportRecords.getReportId();
// String excelName = String.format("本地卡異地市消費_%s(%s至%s)_%s.xlsx", issuer.getName(), beginTime,endTime,reportRecordsId);
// String zipName = String.format("本地卡異地市消費_%s(%s至%s)_%s.zip", issuer.getName(), beginTime,endTime,reportRecordsId);
String excelName = String.format("bdkydsxf_%s_%s-%s_%s.xlsx", issuer.getIssuerNumber(), beginTime,endTime,reportRecordsId);
String zipName = String.format("bdkydsxf_%s_%s-%s_%s.zip", issuer.getIssuerNumber(), beginTime,endTime,reportRecordsId);
String fileName = new String(excelName.getBytes(), "utf-8");
zipName = new String(zipName.getBytes(), "utf-8");
Sheet currentSheet = wb.getSheetAt(0);
int rowNum = 1;
Row row ;
//循環獲取產生每頁數據
List<DetailsTrans> resultList;
boolean hasRechargeData = false;
//循環獲取產生每頁數據
for (int pageNum=1 ; ; pageNum++) {
Pagination page = new Pagination<>(DetailsSqlProvider.buildQueryIbmsLocalAtOutTrans(), pageNum,pageSize, jdbcTemplate, 0, DetailsTrans.class,
issuerId,issuer.getIssuerNumber(), beginTime+" 00:00:00" , endTime +" 23:59:59");
resultList = page.getResultList();
if(pageNum == 1) {
sbf.append("sql:").append(DetailsSqlProvider.buildQueryIbmsLocalAtOutTrans()).append("para:").append(issuerId).append(",")
.append(issuer.getIssuerNumber()).append(",").append(beginTime+" 00:00::00").append(",").append(endTime +" 23:59:59");
}
if(pageNum == 1 && resultList.size()>0){
hasData = true;
}
if(resultList.size()==0){
//合計行
if(hasData){
ExcelUtils.sumRow(currentSheet,wb,rowNum,"N");
}
break;
}
// 明細行
for (DetailsTrans summary : resultList ) {
POIUtils.copyRow(currentSheet, rowNum, rowNum + 1);
row = currentSheet.getRow(rowNum++);
inputLocalAtOut(row, summary);
}
resultList.clear();
}
// 輸出Excel
String absolutePath = ExcelUtils.writeExcel(wb, fileDirectory,fileName);
//轉換zip
List<String> fileNames =new ArrayList<>();
fileNames.add(absolutePath);
boolean result = ZipCompressorUtil.compressFiles(fileNames, fileDirectory+ File.separator+zipName);
if (!result) {
loginfo = "打包文件失敗";
reportRecordsService.markEndTime(reportRecordsId,4);
return;
}
// 添加或者更新報表記錄
reportRecordsService.markFilePath(reportRecordsId,zipName,fileDirectory+ File.separator+zipName);
logger.info("****** ibms 本地卡異地市消費查詢報表完成,交易時間: {}至{}", beginTime,endTime);
loginfo="執行成功";
reportRecordsService.markEndTime(reportRecordsId,3);
} catch (Exception ex) {
reportRecordsService.markEndTime(reportRecordsId,4);
OutputStream os = new ByteArrayOutputStream();
ex.printStackTrace(new PrintStream(os));
loginfo ="執行失敗:"+ os.toString();
throw new InternalException(ex);
} finally {
if (wb != null) {
try {
wb.close();
} catch (Exception ex) {
}
}
reportExcutLogService.saveReportExcutLog(reportRecordsId,loginfo,sbf.toString());
}
}
/**
* imbs 本地卡異地交易明細
*/
private void inputLocalAtOut(final Row row, final DetailsTrans summary) {
Cell cell = row.getCell(0);
cell.setCellValue(summary.getSn());
cell = row.getCell(1);
cell.setCellValue(summary.getIssuerName());
cell = row.getCell(2);
cell.setCellValue(summary.getAcqName());
cell = row.getCell(3);
cell.setCellValue(summary.getBusCom());
cell = row.getCell(4);
cell.setCellValue(summary.getTermNo());
cell = row.getCell(5);
cell.setCellValue(summary.getCardType());
cell = row.getCell(6);
cell.setCellValue(summary.getCardNo());
cell = row.getCell(7);
cell.setCellValue(summary.getTransNo());
cell = row.getCell(8);
cell.setCellValue(summary.getCardForm());
cell = row.getCell(9);
cell.setCellValue(summary.getBeforeAmount());
cell = row.getCell(10);
cell.setCellValue(summary.getAmount());
cell = row.getCell(11);
cell.setCellValue(summary.getAfterAmount());
cell = row.getCell(12);
cell.setCellValue(summary.getTransTime());
cell = row.getCell(13);
cell.setCellValue(summary.getClearTime());
cell = row.getCell(14);
cell.setCellValue(summary.getStatus());
cell = row.getCell(15);
cell.setCellValue(summary.getRecordType());
cell = row.getCell(16);
cell.setCellValue(summary.getCardUsage());
cell = row.getCell(17);
cell.setCellValue(summary.getUpDownFlag());
cell = row.getCell(18);
cell.setCellValue(summary.getStationNo());
cell = row.getCell(19);
cell.setCellValue(summary.getEscapeCityCode());
cell = row.getCell(20);
cell.setCellValue(summary.getEscapeIssuerFlag());
cell = row.getCell(21);
cell.setCellValue(summary.getEscapeStation());
cell = row.getCell(22);
cell.setCellValue(summary.getEscapeTerminalNo());
cell = row.getCell(23);
cell.setCellValue(summary.getEscapeDealTime());
cell = row.getCell(24);
cell.setCellValue(summary.getEscapeDirectionFlag());
cell = row.getCell(25);
cell.setCellValue(summary.getEscapeLineNo());
cell = row.getCell(26);
cell.setCellValue(summary.getEscapeBusNo());
cell = row.getCell(27);
cell.setCellValue(summary.getTicketTimes());
cell = row.getCell(28);
cell.setCellValue(summary.getTicketType());
cell = row.getCell(29);
cell.setCellValue(summary.getTicketDate());
cell = row.getCell(30);
cell.setCellValue(summary.getStationName());
cell = row.getCell(31);
cell.setCellValue(summary.getLongitude());
cell = row.getCell(32);
cell.setCellValue(summary.getLatitude());
}
}
/** * POI 公用方法 * * @author yuxc */ public class POIUtils { /** * 根據模板創建workbook * @param template 模板文件地址 * @return * @throws IOException */ public static Workbook createWorkBook(File template) throws IOException{ Workbook wb = null; try { wb = new HSSFWorkbook(new FileInputStream(template)); } catch (OfficeXmlFileException oex) { try { wb = new XSSFWorkbook(new FileInputStream(template)); } catch (IOException e) { e.printStackTrace(); } } return wb; } /** * Excel的工作表裏複製行 * * @param sheet Excel的工作表 * @param sourceRowNum 要複製的行號(0開始) * @param destRowNum 目標行號(0開始) */ public static final void copyRow(final Sheet sheet, final int sourceRowNum, final int destRowNum) { final int lastRowNum = sheet.getLastRowNum(); if (destRowNum <= lastRowNum) { sheet.shiftRows(destRowNum, sheet.getLastRowNum(), 1); } final Row sourceRow = sheet.getRow(sourceRowNum); // 要複製的行 final Row destRow = sheet.createRow(destRowNum); // 目標行 final int lastCellNum = sourceRow.getLastCellNum(); for (int i = 0; i < lastCellNum; i++) { Cell sourceCell = sourceRow.getCell(i); // 要複製的單元格 Cell destCell = destRow.getCell(i); // 目標單元格 if (sourceCell != null) { if (destCell == null) { destCell = destRow.createCell(i); } destCell.setCellType(sourceCell.getCellType()); destCell.setCellStyle(sourceCell.getCellStyle()); if (sourceCell.getCellType() == Cell.CELL_TYPE_FORMULA) { if (!StringUtils.isBlank(sourceCell.getCellFormula())) { // 有公式 destCell.setCellFormula(getResolvedFormula(sourceCell.getCellFormula(), sourceRowNum, destRowNum)); } } boolean merge = false; // 是否需要合併,已合併過的不再合併 for (int j = 0, k = sheet.getNumMergedRegions(); j < k; j++) { if (sheet.getMergedRegion(j).isInRange(destRowNum, i)) { merge = true; } } if (!merge) { // 查看是否需要合併 for (int j = 0, k = sheet.getNumMergedRegions(); j < k; j++) { final CellRangeAddress rangeAddress = sheet.getMergedRegion(j); if (rangeAddress.isInRange(sourceRowNum, i)) { // 要複製的單元格是合併的,被複制的也要合併 sheet.addMergedRegion(new CellRangeAddress(destRowNum, destRowNum, rangeAddress.getFirstColumn(), rangeAddress.getLastColumn())); break; } } } } } } /** * 實現sheet之間的複製 * @param sheetFrom 原sheet * @param sheetTo 目標sheet * @return 拷貝後的sheet */ public static Sheet copySheet(Sheet sheetFrom, Sheet sheetTo) { CellRangeAddress region = null; Row rowFrom = null; Row rowTo = null; Cell cellFrom = null; Cell cellTo = null; for (int i = 0; i < sheetFrom.getNumMergedRegions(); i++) { region = sheetFrom.getMergedRegion(i); if ((region.getFirstColumn() >= sheetFrom.getFirstRowNum()) && (region.getLastRow() <= sheetFrom.getLastRowNum())) { sheetTo.addMergedRegion(region); } } for (int intRow = sheetFrom.getFirstRowNum(); intRow < sheetFrom.getLastRowNum(); intRow++) { rowFrom = sheetFrom.getRow(intRow); rowTo = sheetTo.createRow(intRow); if (null == rowFrom) { continue; } rowTo.setHeight(rowFrom.getHeight()); for (int intCol = 0; intCol < rowFrom.getLastCellNum(); intCol++) { sheetTo.setDefaultColumnStyle(intCol, sheetFrom.getColumnStyle(intCol)); sheetTo.setColumnWidth(intCol, sheetFrom.getColumnWidth(intCol)); cellFrom = rowFrom.getCell(intCol); cellTo = rowTo.createCell(intCol); if (null == cellFrom) { continue; } cellTo.setCellStyle(cellFrom.getCellStyle()); cellTo.setCellType(cellFrom.getCellType()); switch (cellFrom.getCellType()) { case HSSFCell.CELL_TYPE_STRING: cellTo.setCellValue(StringUtils.trim(cellFrom.getRichStringCellValue().getString())); break; case HSSFCell.CELL_TYPE_NUMERIC: cellTo.setCellValue(cellFrom.getNumericCellValue()); break; case HSSFCell.CELL_TYPE_BOOLEAN: cellTo.setCellValue(cellFrom.getBooleanCellValue()); break; case HSSFCell.CELL_TYPE_FORMULA: // Cell公式不處理 // final FormulaEvaluator evaluator = cellFrom.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator(); // final CellValue cv = evaluator.evaluate(cellFrom); // switch (cv.getCellType()) { // case HSSFCell.CELL_TYPE_STRING: // cellTo.setCellValue(StringUtils.trim(cv.getStringValue())); // break; // case HSSFCell.CELL_TYPE_NUMERIC: // cellTo.setCellValue(cv.getNumberValue()); // break; // case HSSFCell.CELL_TYPE_BOOLEAN: // cellTo.setCellValue((cv.getBooleanValue())); // break; // default: // } // break; default: } } } //sheetTo.setDisplayGridlines(false); //sheetTo.setZoom(80, 100); return sheetTo; } /** * 通過{@link HttpServletResponse}輸出{@code Workbook}到客戶端 */ public static final void write(final HttpServletResponse response, final Workbook workbook, final String fileName) { response.reset(); response.setContentType("application/vnd.ms-excel"); OutputStream os = null; try { String fileExtension = Constant.EXCEL_FILE_EXTENSION; if (HSSFWorkbook.class.isAssignableFrom(workbook.getClass())) { fileExtension = Constant.OLD_EXCEL_FILE_EXTENSION; } response.setHeader("Content-disposition", "attachment; filename=\"" + new String(fileName.getBytes("gb2312"), "iso8859-1") + "." + fileExtension + "\""); os = response.getOutputStream(); workbook.write(os); os.flush(); } catch (IOException ioe) { throw new InternalException(ioe); } finally { if (os != null) { try { os.close(); } catch (IOException ioe) { /** ignore **/ } } } } /** * 在服務器指定文件夾下面創建報表文件 */ public static final void write(final String fileTargetPath, final Workbook workbook, final String fileName) { OutputStream os = null; try { File file = new File(String.format("%s%s%s", fileTargetPath, File.separator, fileName)); File fileParent = file.getParentFile(); if (!fileParent.exists()) { fileParent.mkdirs(); } file.createNewFile(); os = new FileOutputStream(file); workbook.write(os); os.flush(); } catch (IOException ioe) { throw new InternalException(ioe); } finally { if (os != null) { try { os.close(); } catch (IOException ioe) { /** ignore **/ } } } } /** * 獲取Excel中單元格的數據 */ public static final <T> T getCellValue(final Cell cell, final Class<T> clazz) { Object cellValue = ""; if (cell != null) { // cell can be null. switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_STRING: cellValue = StringUtils.trim(cell.getRichStringCellValue().getString()); break; case HSSFCell.CELL_TYPE_NUMERIC: if (Date.class.isAssignableFrom(clazz)) { cellValue = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());//獲取成DATE類型 } else { cellValue = "" + cell.getNumericCellValue(); } break; case HSSFCell.CELL_TYPE_BOOLEAN: cellValue = String.valueOf(cell.getBooleanCellValue()); break; case HSSFCell.CELL_TYPE_FORMULA: // Cell公式要特殊處理 final FormulaEvaluator evaluator = cell.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator(); final CellValue cv = evaluator.evaluate(cell); switch (cv.getCellType()) { case HSSFCell.CELL_TYPE_STRING: cellValue = StringUtils.trim(cv.getStringValue()); break; case HSSFCell.CELL_TYPE_NUMERIC: cellValue = "" + cv.getNumberValue(); break; case HSSFCell.CELL_TYPE_BOOLEAN: cellValue = String.valueOf(cv.getBooleanValue()); break; default: cellValue = null; } break; default: cellValue = ""; } } final T value = (T) ConvertUtils.convert(cellValue, clazz); if (Number.class.isAssignableFrom(clazz) && value == null) { return (T) ConvertUtils.convert("0", clazz); } return value; } /** * 獲取單元格樣式 * @param workbook 工作表 * @param type 單元格值類型 0-數量 1-逗號金額 2-普通金額 3-大寫人民幣符號格式 * @return */ public static CellStyle getCellStyle(final Workbook workbook, final Cell cell, final Integer type) { CellStyle style = cell.getCellStyle(); switch (type) { case 0: style.setDataFormat(workbook.createDataFormat().getFormat("0")); break; case 1: style.setDataFormat(workbook.createDataFormat().getFormat("#,##0.00")); break; case 2: style.setDataFormat(workbook.createDataFormat().getFormat("0.00")); break; case 3: style.setDataFormat(workbook.createDataFormat().getFormat("¥#,##0.00;¥-#,##0.00")); break; default: break; } return style; } /************************************************************************************** * 私有方法 **************************************************************************************/ /** * Excel複製行時調整公式,假定公式只對該行的進行操作<br> * 如第三行的一個公式ROUND((A3+G3), 2)複製到第五行後要更新成ROUND((A5+G5), 2) */ private static final String getResolvedFormula(final String formula, final int sourceRowNum, final int destRowNum) { final Pattern p = Pattern.compile("[a-zA-Z]" + (sourceRowNum + 1) + "(\\D|$)"); final Matcher m = p.matcher(formula); String resolvedFormula = formula; while (m.find()) { // 如果查找到,就替換第一個 resolvedFormula = StringUtils.replaceOnce(resolvedFormula, "" + (sourceRowNum + 1), "" + (destRowNum + 1), m.start()); } return resolvedFormula; } /** * 獲取特定的單元格樣式 * * @param wb 工作簿 * @param type 樣式種類 0-藍色字體 1-紅色 * @return */ public static CellStyle getCellFontStyle(Workbook wb, Integer type) { CellStyle style = wb.createCellStyle(); style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 垂直 style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 水平 style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下邊框 style.setBorderLeft(HSSFCellStyle.BORDER_THIN); // 左邊框 style.setBorderTop(HSSFCellStyle.BORDER_THIN); // 上邊框 style.setBorderRight(HSSFCellStyle.BORDER_THIN); // 右邊框 //生成一個字體 Font font = wb.createFont(); // 字體 font.setFontName("微軟雅黑"); // 默認爲黑色 if (0 == type) { font.setColor(HSSFColor.BLUE.index); } else if (1 == type){ font.setColor(HSSFColor.RED.index); } else { font.setColor(HSSFColor.BLACK.index); } font.setFontHeightInPoints((short)10); style.setFont(font); return style; } }
public class Pagination<T> { //一頁顯示的記錄數 private int numPerPage = 100; //記錄總數 private int totalRows; //總頁數 private int totalPages; //當前頁碼 private int currentPage = 1; //起始行數 private int startIndex = 0; //結束行數 private int lastIndex; //結果集存放List private List<T> resultList = new ArrayList<T>(); private static final Logger logger = LoggerFactory.getLogger(Pagination.class); /**分頁構造函數 * @param sql 根據傳入的sql語句得到一些基本分頁信息 * @param currentPage 當前頁 * @param numPerPage 每頁記錄數 * @param jdbcTemplate 實例 * @param dataBaseType 數據庫類型 0-mysql 1-oracle */ public Pagination(String sql, int currentPage, int numPerPage, JdbcTemplate jdbcTemplate, Integer dataBaseType, Class<T> returnType, Object... args){ if (jdbcTemplate == null) { throw new IllegalArgumentException("jdbcTemplate不能爲空"); } else if (StringUtils.isEmpty(sql)) { throw new IllegalArgumentException("分頁查詢SQL不能爲空"); } //設置每頁顯示記錄數 setNumPerPage(numPerPage); //設置要顯示的頁數 setCurrentPage(currentPage); //計算總記錄數 StringBuffer totalSql = new StringBuffer(" SELECT COUNT(1) FROM ( \n "); totalSql.append(sql).append("\n"); totalSql.append(" ) AS TOTAL_TABLE "); //總記錄數 if (args != null) { setTotalRows(jdbcTemplate.queryForObject(totalSql.toString(), Integer.class, args)); } else { setTotalRows(jdbcTemplate.queryForObject(totalSql.toString(), Integer.class)); } //計算總頁數 setTotalPages(); //計算起始行數 setStartIndex(); //計算結束行數 setLastIndex(); String querySql = ""; if (0 == dataBaseType) { querySql = getMySqlPageSql(sql, numPerPage); } else { querySql = getOraclePageSql(sql); } logger.info("querySql="+querySql); //裝入結果集 setResultList(jdbcTemplate.query(querySql, new BeanPropertyRowMapper<T>(returnType), args)); } /** * 構造MySQL數據分頁SQL * @param dataSql 查詢數據SQL * @param pageSize * @return */ private String getMySqlPageSql(String dataSql, Integer pageSize) { StringBuilder stringBuilder = new StringBuilder(dataSql) .append(" LIMIT ").append(startIndex); if (pageSize != null) { stringBuilder.append(", ").append(pageSize); } return stringBuilder.toString(); } /** * 構造oracle分頁查詢語句 * @param dataSql 原始查詢sql * @return 分頁sql */ private String getOraclePageSql(final String dataSql) { //構造oracle數據庫的分頁語句 StringBuffer sql = new StringBuffer(" SELECT * FROM ( ").append("\n") .append(" SELECT TEMP.* , ROWNUM NUM FROM ( ").append("\n") .append(dataSql).append("\n") .append(" ) TEMP WHERE ROWNUM <= ").append(lastIndex).append("\n") .append(") WHERE NUM > ").append(startIndex); return sql.toString(); } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getNumPerPage() { return numPerPage; } public void setNumPerPage(int numPerPage) { this.numPerPage = numPerPage; } public List<T> getResultList() { return resultList; } public void setResultList(List<T> resultList) { this.resultList = resultList; } public int getTotalPages() { return totalPages; } //計算總頁數 public void setTotalPages() { if(totalRows % numPerPage == 0){ this.totalPages = totalRows / numPerPage; }else{ this.totalPages = (totalRows / numPerPage) + 1; } } public int getTotalRows() { return totalRows; } public void setTotalRows(int totalRows) { this.totalRows = totalRows; } public int getStartIndex() { return startIndex; } public void setStartIndex() { this.startIndex = (currentPage - 1) * numPerPage; } public int getLastIndex() { return lastIndex; } //計算結束時候的索引 public void setLastIndex() { if ( totalRows < numPerPage){ this.lastIndex = totalRows; } else if ((totalRows % numPerPage == 0) || (totalRows % numPerPage != 0 && currentPage < totalPages)){ this.lastIndex = currentPage * numPerPage; } else if (totalRows % numPerPage != 0 && currentPage == totalPages) { //最後一頁 this.lastIndex = totalRows ; } } }
public class ExcelUtils { public static String writeExcel(Workbook wb, String fileDirectory, String fileName) throws Exception { // 輸出Excel //String fileDirectory = baseFilePath + File.separator + "period"; File fileDir = new File(fileDirectory); if (!fileDir.exists()) { fileDir.mkdir(); } fileDirectory = String.format("%s%s", fileDirectory, File.separator); File fileDelete = new File(fileDirectory + fileName); if (fileDelete.exists() || fileDelete.isFile()) { fileDelete.delete(); } POIUtils.write(fileDirectory, wb, fileName); return fileDirectory + fileName; } /** * 合計行 */ public static void sumRow(Sheet currentSheet, Workbook wb, int rowNum, String colume){ Row row = currentSheet.getRow(rowNum+2); Cell cell = row.getCell(1); cell.setCellValue(rowNum-1); cell = row.getCell(4); cell.setCellType(Cell.CELL_TYPE_FORMULA); String formula = String.format("SUM(%s2:%s%d)",colume,colume, rowNum); cell.setCellStyle(POIUtils.getCellStyle(wb, cell, 1)); cell.setCellFormula(formula); currentSheet.setForceFormulaRecalculation(true); } }
public class ZipCompressorUtil { private static final Logger logger = Logger .getLogger(ZipCompressorUtil.class.getName()); /** * 文件壓縮,壓縮成功返回true,否則false,壓縮後刪除原文件 * * @return * @author Liuxueliang/Jul 9, 2014/4:02:14 PM */ public static boolean compress(String srcFileName, String zipFileName) { File srcFile = new File(srcFileName); if (!srcFile.exists()) { logger.error("要壓縮餓文件不存在,filename:" + srcFile); } try { File zipFile = new File(zipFileName); // 壓縮文件若存在就刪除,重新生成 if (zipFile.exists()) { zipFile.delete(); } Project prj = new Project(); Zip zip = new Zip(); zip.setProject(prj); zip.setDestFile(zipFile); // 壓縮哪些文件 FileSet fileSet = new FileSet(); fileSet.setProject(prj); fileSet.setFile(srcFile); zip.addFileset(fileSet); zip.execute(); srcFile.delete(); return true; } catch (Exception e) { logger.error("file zipCompressor filed,filename:" + srcFileName); return false; } } /** * 文件壓縮,壓縮成功返回true,否則false,壓縮後刪除原文件 * @return * @author Liuxueliang/Jul 9, 2014/4:02:14 PM */ public static boolean compressFiles(List<String> srcFileNameList, String zipFileName) { File zipFile = new File(zipFileName); // 壓縮文件若存在就刪除,重新生成 if (zipFile.exists()) { zipFile.delete(); } Project prj = new Project(); Zip zip = new Zip(); zip.setProject(prj); zip.setDestFile(zipFile); // 壓縮哪些文件 FileSet fileSet = new FileSet(); for (String srcFileName : srcFileNameList) { File srcFile = new File(srcFileName); if (!srcFile.exists()) { logger.error("要壓縮餓文件不存在,filename:" + srcFile); return false; } fileSet.setFile(srcFile); } zip.addFileset(fileSet); zip.execute(); for (String srcFileName : srcFileNameList) { File srcFile = new File(srcFileName); if (!srcFile.exists()) { continue; } srcFile.delete(); } return true; } public static void main(String[] args) { // ZipCompressorUtil.compress("d:\\data\\19e_2013082811.csv", // "d:\\data\\19e_20130828" + ".zip"); List<String> list = new ArrayList<String>(); list.add("D:/1.txt"); list.add("D:/2.txt"); list.add("D:/3.txt"); list.add("D:/4.txt"); list.add("D:/5.txt"); list.add("D:/6.txt"); list.add("D:/7.txt"); ZipCompressorUtil.compressFiles(list, "D:/123.zip"); } }