POIUtil.java 11.2 KB
Newer Older
eddie.woo's avatar
eddie.woo committed
1 2
package pwc.taxtech.atms.common;

chase's avatar
chase committed
3
import org.apache.commons.collections.CollectionUtils;
eddie.woo's avatar
eddie.woo committed
4 5
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
chase's avatar
chase committed
6
import org.apache.poi.ss.usermodel.*;
chase's avatar
chase committed
7
import org.apache.poi.ss.util.CellRangeAddress;
eddie.woo's avatar
eddie.woo committed
8 9 10 11
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

chase's avatar
chase committed
12
import java.util.Iterator;
chase's avatar
chase committed
13
import java.util.List;
eddie.woo's avatar
eddie.woo committed
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
import java.util.Optional;

public class POIUtil {
    private static final Logger logger = LoggerFactory.getLogger(POIUtil.class);
    public static final String XLSX = ".xlsx";
    public static final String XLS = ".xls";

    public static Optional<Workbook> cloneNewSheet(Sheet sheet, String fileName) {
        Workbook workbook;
        try {
            if (StringUtils.endsWith(fileName, XLSX)) {
                workbook = new XSSFWorkbook();
            } else if (StringUtils.endsWith(fileName, XLS)) {
                workbook = new HSSFWorkbook();
            } else {
                return Optional.empty();
            }
            Sheet tmpSheet = workbook.createSheet(sheet.getSheetName());
            cloneSheet(sheet, tmpSheet);
            return Optional.of(workbook);
        } catch (Exception e) {
            logger.error("cloneNewSheet error.", e);
        }
        return Optional.empty();
    }

    public static void cloneSheet(Sheet sheet, Sheet targetSheet) {
        for (int r = sheet.getFirstRowNum(); r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
eddie.woo's avatar
eddie.woo committed
43 44 45
            if (null == row) {
                continue;
            }
eddie.woo's avatar
eddie.woo committed
46 47
            Row targetRow = targetSheet.createRow(r);
            for (int c = row.getFirstCellNum(); c <= row.getLastCellNum(); c++) {
zhkwei's avatar
zhkwei committed
48 49 50
                if(c < 0 ){
                    continue;
                }
eddie.woo's avatar
eddie.woo committed
51
                Cell cell = row.getCell(c);
52
                if (null == cell) {
eddie.woo's avatar
eddie.woo committed
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
                    continue;
                }
                Cell targetCell = targetRow.createCell(c);
                targetCell.setCellType(cell.getCellTypeEnum());
                switch (cell.getCellTypeEnum()) {
                    case STRING:
                        targetCell.setCellValue(cell.getStringCellValue());
                        break;
                    case NUMERIC:
                        targetCell.setCellValue(cell.getNumericCellValue());
                        break;
                    case BOOLEAN:
                        targetCell.setCellValue(cell.getBooleanCellValue());
                        break;
                    case FORMULA:
                        targetCell.setCellFormula(cell.getCellFormula());
                        break;
//                    case ERROR:
////                    case BLANK:
////                    case _NONE:
                    default:
                        break;
                }
                if (null != cell.getCellComment()) {
                    targetCell.setCellComment(cell.getCellComment());
                }
kevin's avatar
kevin committed
79 80 81 82 83 84
                if (null != cell.getCellStyle() && targetCell.getCellStyle() != null ) {
                    try{
                        targetCell.getCellStyle().cloneStyleFrom(cell.getCellStyle());
                    }catch (Exception e){
                        //e.printStackTrace();
                    }
eddie.woo's avatar
eddie.woo committed
85 86 87 88 89 90 91 92
                }
                if (null != cell.getHyperlink()) {
                    targetCell.setHyperlink(cell.getHyperlink());
                }
            }
        }
    }

chase's avatar
chase committed
93
    public static void cloneSheetAndStyle(Sheet sheet, Sheet targetSheet,Workbook tWorkbook) {
chase's avatar
chase committed
94 95 96 97 98 99 100
        //设置合并单元格
        List<CellRangeAddress> merges =  sheet.getMergedRegions();
        if(CollectionUtils.isNotEmpty(merges)){
            for(CellRangeAddress merge : merges){
                targetSheet.addMergedRegion(merge);
            }
        }
chase's avatar
chase committed
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
        for (int r = sheet.getFirstRowNum(); r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
            if (null == row) {
                continue;
            }
            Row targetRow = targetSheet.createRow(r);
            for (int c = row.getFirstCellNum(); c <= row.getLastCellNum(); c++) {
                if(c < 0 ){
                    continue;
                }
                Cell cell = row.getCell(c);
                if (null == cell) {
                    continue;
                }
                Cell targetCell = targetRow.createCell(c);
                targetCell.setCellType(cell.getCellTypeEnum());
                switch (cell.getCellTypeEnum()) {
                    case STRING:
                        if (cell.getStringCellValue().indexOf("KeyIn")>0){
                            targetCell.setCellValue("");
                        }else{
                            targetCell.setCellValue(cell.getStringCellValue());
                        }
                        break;
                    case NUMERIC:
                        targetCell.setCellValue(cell.getNumericCellValue());
                        break;
                    case BOOLEAN:
                        targetCell.setCellValue(cell.getBooleanCellValue());
                        break;
                    case FORMULA:
                        targetCell.setCellFormula(cell.getCellFormula());
                        break;
//                    case ERROR:
////                    case BLANK:
////                    case _NONE:
                    default:
                        break;
                }
                if (null != cell.getCellComment()) {
                    targetCell.setCellComment(cell.getCellComment());
                }
                if (null != cell.getCellStyle()) {
                    CellStyle newstyle=tWorkbook.createCellStyle();
                    targetCell.setCellStyle(newstyle);
                    try{
                        targetCell.getCellStyle().cloneStyleFrom(cell.getCellStyle());
                    }catch (Exception e){
                        //e.printStackTrace();
                    }
                }
                if (null != cell.getHyperlink()) {
                    targetCell.setHyperlink(cell.getHyperlink());
                }
            }
        }
    }
eddie.woo's avatar
eddie.woo committed
158 159 160
    public static String getCellFormulaString(Cell cell) {
        switch (cell.getCellTypeEnum()) {
            case STRING:
frank.xa.zhang's avatar
frank.xa.zhang committed
161
                return cell.getStringCellValue();
eddie.woo's avatar
eddie.woo committed
162
            case FORMULA:
frank.xa.zhang's avatar
frank.xa.zhang committed
163
                return cell.getCellFormula();
eddie.woo's avatar
eddie.woo committed
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
            case BLANK:
                return cell.getStringCellValue();
            case NUMERIC:
                return String.valueOf(cell.getNumericCellValue());
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            default:
                return StringUtils.EMPTY;
        }
    }

    public static Optional<String> getFileSuffix(String fileName) {
        if (StringUtils.endsWith(fileName, XLSX)) {
            return Optional.of(XLSX);
        } else if (StringUtils.endsWith(fileName, XLS)) {
            return Optional.of(XLS);
        } else {
            return Optional.empty();
        }
    }
184 185 186 187 188 189 190 191 192 193 194

    public static Row createRow(Sheet sheet, Integer rowIndex) {
        Row row = null;
        if (sheet.getRow(rowIndex) != null) {
            int lastRowNo = sheet.getLastRowNum();
            sheet.shiftRows(rowIndex, lastRowNo, 1);
        }
        row = sheet.createRow(rowIndex);
        return row;
    }

chase's avatar
chase committed
195
    public static Row createAndCloneRow(Workbook wb , Sheet sheet, Integer destRowIndex, Row fromRow) {
chase's avatar
chase committed
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
        Row toRow = null;
        if (sheet.getRow(destRowIndex) != null) {
            int lastRowNo = sheet.getLastRowNum();
            sheet.shiftRows(destRowIndex, lastRowNo, 1);
        }
        toRow = sheet.createRow(destRowIndex);
        for (Iterator cellIt = fromRow.cellIterator(); cellIt.hasNext();) {
            Cell tmpCell = (Cell) cellIt.next();
            Cell newCell = toRow.createCell(tmpCell.getColumnIndex());
            copyCell(wb, tmpCell, newCell, false);
        }
        return toRow;
    }

    public static void copyCell(Workbook wb,Cell srcCell, Cell distCell,
                                boolean copyValueFlag) {
        CellStyle newstyle=wb.createCellStyle();
chase's avatar
chase committed
213 214
        newstyle.cloneStyleFrom(srcCell.getCellStyle());
//        copyCellStyle(wb,srcCell.getCellStyle(), newstyle);
chase's avatar
chase committed
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
//        distCell.setEncoding(srcCell.getEncoding());
        //样式
        distCell.setCellStyle(newstyle);
        //评论
        if (srcCell.getCellComment() != null) {
            distCell.setCellComment(srcCell.getCellComment());
        }
        // 不同数据类型处理
        int srcCellType = srcCell.getCellType();
        distCell.setCellType(srcCellType);
        if (copyValueFlag) {
            if (srcCellType == Cell.CELL_TYPE_NUMERIC) {
                if (DateUtil.isCellDateFormatted(srcCell)) {
                    distCell.setCellValue(srcCell.getDateCellValue());
                } else {
                    distCell.setCellValue(srcCell.getNumericCellValue());
                }
            } else if (srcCellType == Cell.CELL_TYPE_STRING) {
                distCell.setCellValue(srcCell.getRichStringCellValue());
            } else if (srcCellType == Cell.CELL_TYPE_BLANK) {
                // nothing21
            } else if (srcCellType == Cell.CELL_TYPE_BOOLEAN) {
                distCell.setCellValue(srcCell.getBooleanCellValue());
            } else if (srcCellType == Cell.CELL_TYPE_ERROR) {
                distCell.setCellErrorValue(srcCell.getErrorCellValue());
            } else if (srcCellType == Cell.CELL_TYPE_FORMULA) {
                distCell.setCellFormula(srcCell.getCellFormula());
            } else { // nothing29
            }
        }
    }

    public static void copyCellStyle(Workbook wb,CellStyle fromStyle,
                                     CellStyle toStyle) {
        toStyle.setAlignment(HorizontalAlignment.forInt(fromStyle.getAlignment()));
        //边框和边框颜色
        toStyle.setBorderBottom(BorderStyle.valueOf(fromStyle.getBorderBottom()));
        toStyle.setBorderLeft(BorderStyle.valueOf(fromStyle.getBorderLeft()));
        toStyle.setBorderRight(BorderStyle.valueOf(fromStyle.getBorderRight()));
        toStyle.setBorderTop(BorderStyle.valueOf(fromStyle.getBorderTop()));
        toStyle.setTopBorderColor(fromStyle.getTopBorderColor());
        toStyle.setBottomBorderColor(fromStyle.getBottomBorderColor());
        toStyle.setRightBorderColor(fromStyle.getRightBorderColor());
        toStyle.setLeftBorderColor(fromStyle.getLeftBorderColor());

        //背景和前景
        toStyle.setFillBackgroundColor(fromStyle.getFillBackgroundColor());
        toStyle.setFillForegroundColor(fromStyle.getFillForegroundColor());
//
        toStyle.setDataFormat(fromStyle.getDataFormat());
        toStyle.setFillPattern(FillPatternType.forInt(fromStyle.getFillPattern()));
		toStyle.setFont(wb.getFontAt(fromStyle.getFontIndex()));
        toStyle.setHidden(fromStyle.getHidden());
        toStyle.setIndention(fromStyle.getIndention());//首行缩进
        toStyle.setLocked(fromStyle.getLocked());
        toStyle.setRotation(fromStyle.getRotation());//旋转
        toStyle.setVerticalAlignment(VerticalAlignment.forInt(fromStyle.getVerticalAlignment()));
        toStyle.setWrapText(fromStyle.getWrapText());

    }
275 276


eddie.woo's avatar
eddie.woo committed
277
}