JAVA实现EXCEL方法二-HSSFWorkbook+模板

使用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");
   }

}

猜你喜欢

转载自wujt.iteye.com/blog/2422648