POI處理Excel工具類


TOC

POI處理Excel

工具類

/**
* @author jsy
* @date 2018/8/30 15:13
* @description poi導出表格工具類
*/
@Slf4j
public class PoiUtils {


   /**
     * 導出(前端導出)
     */
    public static void export(HttpServletResponse response, HttpServletRequest request, Workbook wb, String fileName) throws Exception {
        String s = DateUtils.formatDate(new Date(), DateUtils.YYYYMMDD_NO_LINE);
        fileName += s;
        response.reset();
        String name = URLEncoder.encode(fileName + ".xls", "UTF-8");
        response.setContentType("application/msexcel");// 定義輸出類型
        if (request.getHeader("User-Agent").toLowerCase().contains("firefox")) {
            response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + name);
        } else {
            response.setHeader("content-disposition", "attachment; filename=" + name);
        }
        OutputStream out = response.getOutputStream();
        wb.write(out);
        out.close();
    }

    /**
     * 導出(本地導出,主要是測試用)
     */
    public static void exportLocal(Workbook wb, String url, String name) throws Exception {
        url = StringUtils.isBlank(url) ? "c:" : url;
        FileOutputStream fileOut = new FileOutputStream(url + "\\\\" + name + ".xls");
        wb.write(fileOut);
        fileOut.close();
    }

    /**
     * 創建標題樣式
     */
    public static CellStyle getTitleStyle(Workbook wb) {
        Font font = wb.createFont();
        font.setFontHeightInPoints((short) 19);
        CellStyle style = wb.createCellStyle();
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setFont(font);
        return style;
    }

    /**
     * 創建居中樣式
     */
    public static CellStyle getjzStyle(Workbook wb) {
        CellStyle style = wb.createCellStyle();
        style.setAlignment(CellStyle.ALIGN_CENTER); // 創建一個居中格式
        style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 垂直居中
        return style;
    }

    /**
     * 創建邊框樣式(上下左右)
     */
    public static CellStyle getBorderStyle(Workbook wb, boolean top, boolean button, boolean left, boolean right, short color, CellStyle style) {
        if (top) {
            style.setBorderTop(CellStyle.BORDER_THIN);
            style.setTopBorderColor(color);
        }
        if (button) {
            style.setBorderBottom(CellStyle.BORDER_THIN);
            style.setBottomBorderColor(color);
        }
        if (left) {
            style.setBorderLeft(CellStyle.BORDER_THIN);
            style.setLeftBorderColor(color);
        }
        if (right) {
            style.setBorderRight(CellStyle.BORDER_THIN);
            style.setRightBorderColor(color);
        }
        return style;
    }

    /**
     * 復制行樣式
     */
    public static Row setRowStyle(Workbook wb, Row row, int start, int end, CellStyle style) {
        Cell cell;
        while (start <= end) {
            cell = row.createCell(start++);
            cell.setCellStyle(style);
        }
        return row;
    }

    /**
     * 讀取模板
     *
     * @param excelName 模板name
     */
    public static Workbook getWorkbook(String excelName) throws Exception {
        InputStream inp = PoiUtils.class.getResourceAsStream("/templates/" + excelName + ".xls");
        return WorkbookFactory.create(inp);
    }


    /**
     * 多行復制
     *
     * @param wb 表格
     * @param sheet 頁
     * @param from 開始行
     * @param to 復制行
     * @param copyValueFlag true則連同cell的內容一起復制
     * @param count 復制的行數
     */
    public static void copyMoreRow(Workbook wb, Sheet sheet, int from, int to, boolean copyValueFlag, int count) {
        Row fromRow, toRow;
        for (int i = 0; i < count; i++) {
            fromRow = sheet.getRow(from + i);
            toRow = sheet.createRow(to + i);

            PoiUtils.copyRow(wb, sheet, fromRow, toRow, copyValueFlag);
        }
    }

    /**
     * 行復制功能
     *
     * @param fromRow 開始行
     * @param toRow 目的行
     * @param copyValueFlag true則連同cell的內容一起復制
     */
    public static void copyRow(Workbook wb, Sheet sheet, Row fromRow, Row toRow, boolean copyValueFlag) {
        toRow.setHeight(fromRow.getHeight());
        for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
            CellRangeAddress cellRangeAddress = sheet.getMergedRegion(i);
            if (cellRangeAddress.getFirstRow() == fromRow.getRowNum()) {
                CellRangeAddress newCellRangeAddress = new CellRangeAddress(toRow.getRowNum(), (toRow.getRowNum() + (cellRangeAddress.getLastRow() - cellRangeAddress.getFirstRow())),
                                                                            cellRangeAddress.getFirstColumn(), cellRangeAddress.getLastColumn());
                sheet.addMergedRegion(newCellRangeAddress);
            }
        }
        for (Iterator cellIt = fromRow.cellIterator(); cellIt.hasNext(); ) {
            Cell tmpCell = (Cell) cellIt.next();
            Cell newCell = toRow.createCell(tmpCell.getColumnIndex());
            copyCell(wb, tmpCell, newCell, copyValueFlag);
        }

    }

    /**
     * 復制單元格
     *
     * @param srcCell 原單元格
     * @param distCell 目的單元格
     * @param copyValueFlag true則連同cell的內容一起復制
     */
    public static void copyCell(Workbook wb, Cell srcCell, Cell distCell, boolean copyValueFlag) {
        CellStyle newstyle = wb.createCellStyle();
        newstyle.cloneStyleFrom(srcCell.getCellStyle());
        // 樣式
        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());
            } // nothing29

        }
    }


    // 獲取值,封裝的方法
    private static String getValue(Cell cell) {
        if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {// 若是Boolean類型
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {// 若是數字類型
            return String.valueOf(cell.getNumericCellValue());
        } else {// 其他格式直接轉換即可
            return String.valueOf(cell.getStringCellValue());
        }
    }

    private static String getString(String aa) {
        if (StringUtils.isBlank(aa)) {
            return "";
        } else {
            return aa;
        }
    }

    private static String getIntString(Integer aa) {
        if (aa == null) {
            return "";
        } else {
            return String.valueOf(aa);
        }
    }

    private static String getDoubleString(Double aa) {
        if (aa == null) {
            return "";
        } else {
            return DataUtils.doubleToString(aa);
        }
    }

    /**
     * 多行復制--多個表格
     *
     * @param wb 表格
     * @param fromSheet 被復制的頁
     * @param toSheet 目的頁
     * @param from 開始行
     * @param to 復制行
     * @param copyValueFlag true則連同cell的內容一起復制
     * @param count 復制的行數
     */
    public static void copyMoreRowToExcel(Workbook wb, Sheet fromSheet, Sheet toSheet, int from, int to, boolean copyValueFlag, int count) {
        Row fromRow, toRow;
        for (int i = 0; i < count; i++) {
            fromRow = fromSheet.getRow(from + i);
            toRow = toSheet.createRow(to + i);
            PoiUtils.copyRowToExcel(wb, fromSheet, toSheet, fromRow, toRow, copyValueFlag);
        }
        fromRow = fromSheet.getRow(1);
        //設置列寬
        for (int i = 0; i < fromRow.getPhysicalNumberOfCells(); i++) {
            toSheet.setColumnWidth(i, fromSheet.getColumnWidth(i));
        }
    }

    /**
     * 行復制功能--兩個表格
     *
     * @param wb 復制到的表格
     * @param fromSheet 被復制的頁
     * @param toSheet 目的頁
     * @param fromRow 原行
     * @param toRow 目的行
     * @param copyValueFlag true則連同cell的內容一起復制
     */
    public static void copyRowToExcel(Workbook wb, Sheet fromSheet, Sheet toSheet, Row fromRow, Row toRow, boolean copyValueFlag) {
        toRow.setHeight(fromRow.getHeight());//設置行高
        for (int i = 0; i < fromSheet.getNumMergedRegions(); i++) {//得到所有區域
            CellRangeAddress cellRangeAddress = fromSheet.getMergedRegion(i);//合並單元格
            if (cellRangeAddress.getFirstRow() == fromRow.getRowNum()) {//若是被合並了的
                CellRangeAddress newCellRangeAddress = new CellRangeAddress(toRow.getRowNum(), (toRow.getRowNum() + (cellRangeAddress.getLastRow() - cellRangeAddress.getFirstRow())),
                                                                            cellRangeAddress.getFirstColumn(), cellRangeAddress.getLastColumn());
                toSheet.addMergedRegion(newCellRangeAddress);
            }
        }
        for (Iterator cellIt = fromRow.cellIterator(); cellIt.hasNext(); ) {
            Cell tmpCell = (Cell) cellIt.next();
            Cell newCell = toRow.createCell(tmpCell.getColumnIndex());
            copyCell(tmpCell, newCell, copyValueFlag);
        }

    }

    /**
     * 復制單元格
     *
     * @param oldCell 原數據
     * @param newCell 目的數據
     * @param ifvalue 是否復制文字
     */
    public static void copyCell(Cell oldCell, Cell newCell, boolean ifvalue) {
        newCell.setCellStyle(oldCell.getCellStyle());
        if (ifvalue) {
            switch (oldCell.getCellType()) {
                case Cell.CELL_TYPE_STRING:
                    newCell.setCellValue(oldCell.getStringCellValue());
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    newCell.setCellValue(oldCell.getNumericCellValue());
                    break;
                case Cell.CELL_TYPE_BLANK:
                    newCell.setCellType(Cell.CELL_TYPE_BLANK);
                    break;
                case Cell.CELL_TYPE_BOOLEAN:
                    newCell.setCellValue(oldCell.getBooleanCellValue());
                    break;
                case Cell.CELL_TYPE_ERROR:
                    newCell.setCellErrorValue(oldCell.getErrorCellValue());
                    break;
                case Cell.CELL_TYPE_FORMULA:
                    newCell.setCellFormula(oldCell.getCellFormula());
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 合並單元格
     *
     * @param sheet
     * @param firstRow
     * @param lastRow
     * @param firstCol
     * @param lastCol
     */
    public static void setMergedRegion(Sheet sheet, int firstRow, int lastRow, int firstCol, int lastCol) {
        Row row;
        Cell cell;
        CellStyle cellStyle = sheet.getRow(firstRow).getCell(firstCol).getCellStyle();
        for (int i = firstRow; i <= lastRow; i++) {
            row = sheet.getRow(i);
            for (int j = firstCol; j <= lastCol; j++) {
                if (i == firstRow && j == firstCol) {
                    continue;
                }
                cell = row.createCell(j);
                cell.setCellStyle(cellStyle);
            }
        }
        sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol, lastCol));
    }


    /**
     * 刪除模板表格(除了 id之外所有的)
     *
     * @param wb
     */
    public static void removeModelSheet(Workbook wb, int id) {
        int numberOfSheets = wb.getNumberOfSheets();
        for (int i = numberOfSheets - 1; i > -1; i--) {
            if (i != id) {
                wb.removeSheetAt(i);
            }
        }
        //設置默認顯示第一頁
        wb.setActiveSheet(0);
    }
    /**
     * 刪除模板表格(除了 name之外所有的)
     *
     * @param wb
     */
    public static void removeModelSheet(Workbook wb, String name) {
        int sheetIndex = wb.getSheetIndex(wb.getSheet(name));
        removeModelSheet(wb,sheetIndex);
    }
    /**
     * 刪除模板表格(除了 name之外所有的)
     *
     * @param wb
     */
    public static void removeModelSheet(Workbook wb, Sheet noDelSheet) {
        int sheetIndex = wb.getSheetIndex(noDelSheet);
        removeModelSheet(wb,sheetIndex);
    }

}

測試

同一個表格內,設置圖片

    private Workbook startExportWhCg(Entity whCg) throws Exception {
        // 讀取模板數據
        Workbook wb = PoiUtils.getWorkbook("demo");
        // 獲取頁
        Sheet sheet = wb.getSheet("頁面1");

        Drawing patriarch = sheet.createDrawingPatriarch();
       PoiUtils.exportWhCg(wb, sheet, patriarch, whCg);
        // 刪除其余的模板
        PoiUtils.removeModelSheet(wb, wb.getSheetIndex(sheet));
        return wb;
    }
    public static void exportWhCg(Workbook wb, Sheet sheet, Drawing patriarch, Entity whCg) throws Exception {

        // 獲取列數
        Row row = sheet.getRow(start + 1);
        row.getCell(2).setCellValue( whCg.getName());
       ....
        /* 遍歷詳情數據 */
        int rowIndex = start + 4;
        for (Detail weightingDetail : whCg.getPageInfo().getList()) {
            Row rowDetail = sheet.getRow(rowIndex++);
            int i = 2, j = 0;
            rowDetail.getCell(i++).setCellValue(weightingDetail.getName());
            ....
        }

         //設置圖片 base64字符串設置圖片
        //位置
         HSSFClientAnchor anchor = new HSSFClientAnchor(400, 5, 0, 254, (short) 2, start + 13, (short) 3, start + 13);
        //設置
         patriarch.createPicture(anchor, wb.addPicture(Base64.decodeBase64(whCg.getStr().substring(17)), HSSFWorkbook.PICTURE_TYPE_JPEG));

    }

不同sheet內(實時設置頁面)

    /**
     * 導出總賬
     *
     * @param response
     * @param request
     * @param re
     * @return
     * @author jingshiyu
     * @date 2020/3/17 17:08
     */
    public void exportQueryGLVoucherData(HttpServletResponse response, HttpServletRequest request, Date date, Integer isNoAccount) throws Exception {
        //查詢數據
        List<AccV> totalList = ...;
        String time = DateUtils.formatDate(date, "yyyy年MM月");
        String s = time + "賬";
        // 導出表格
        // 讀取模板數據
        Workbook wb = PoiUtils.getWorkbook("demo");
        Sheet modelSheet = wb.getSheet("賬2");// 創建頁
        Sheet sheet = wb.createSheet(s);// 創建頁
        final int  row = 18;
        List<AccV> allList = new ArrayList<>();
        for (AccV accVoucherTotal : totalList) {
            allList.add(accVoucherTotal);
            if (CollectionUtils.isNotEmpty(accVoucherTotal.getList())) {
                allList.addAll(accVoucherTotal.getList());
            }

            accVoucherTotal.setList(null);
        }

        //分頁
        int totalPage = (int) Math.ceil(allList.size() * 1.0 / row);
        for (int i = 0; i < totalPage; i++) {
            int start = i * (row + 7);
            //表頭復制
            PoiUtils.copyMoreRowToExcel(wb, modelSheet, sheet, 0, start, true, 4);
            //具體內容行
            for (int j = 0; j < row; j++) {
                PoiUtils.copyRowToExcel(wb, modelSheet, sheet, modelSheet.getRow(4), sheet.createRow(start + 4 + j), false);

            }
            PoiUtils.copyMoreRowToExcel(wb, modelSheet, sheet, 5, start + 4 + row, true, 2);
            //合並
            PoiUtils.setMergedRegion(sheet, start, (start + 4 + row), 4, 4);
//            PoiUtils.setMergedRegion(sheet,start,start+6+row,6,6);
            String page = "單\r\n據\r\n" + (i + 1) + "/" + totalPage;
            //設置內容
            int end = Math.min(allList.size(), (i + 1) * row);
            PoiUtils.exportQueryGLVoucherData(wb, sheet, allList.subList(i * row, end), time, start, page, DateUtils.formatDate(date, DateUtils.CN_DATE));
        }
        // 刪除其余的模板
        PoiUtils.removeModelSheet(wb, s);
        PoiUtils.export(response, request, wb, s);
    }
    public static void exportQueryGLVoucherData(Workbook wb, Sheet sheet, List<AccVoucherTotal> subList, String time, int start, String page, String date) {

        // 獲取列數
        Row row = sheet.getRow(start);
//        row.getCell(0).setCellValue(time + "總賬");
        row.getCell(4).setCellValue(page);
        sheet.getRow(start + 1).getCell(0).setCellValue("日期:" + date);
        sheet.getRow(start + 1).getCell(2).setCellValue("填制日期:" + DateUtils.formatDate(new Date(), DateUtils.CN_DATE));
        /* 遍歷詳情數據 */
            if (CollectionUtils.isNotEmpty(subList)) {
                int rowIndex = start + 4;
//                int c = 0;
                    for (AccVoucherTotal oneRow : subList) {
                        row=sheet.getRow(rowIndex++);
                        int c=0;
                        row.getCell(c++).setCellValue(getString(oneRow.getVn())+getString(oneRow.getName()));
                        row.getCell(c++).setCellValue(getDoubleString(oneRow.getDebitPrice()));
                        row.getCell(c++).setCellValue(getDoubleString(oneRow.getLendPrice()));
                        row.getCell(c).setCellValue(getDoubleString(oneRow.getBalance()));
                    }

            }

    }






免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM