POI實現excel的數據驗證

前言

Apache POI是Apache軟件基金會的開放源碼函式庫,POI提供API給Java程序對Microsoft Office格式檔案讀和寫的功能。
實際開發中,用POI來讀寫excel文檔的比較多。因此,這裏記錄下用POI讀取excel文檔的一些難點作下記錄。excel

難點1:合併單元格

在實際開發中,有時會遇到如圖示例,須要按照如圖所示進行導出excel文件。這就涉及到了合併單元格和給單元格賦值的問題。
code

代碼實現策略:

step 1: 合併單元格

eventSheet.addMergedRegion(new CellRangeAddress(lineNum, fields.size() + lineNum - 1, 1, 1));

step 2: 給單元格賦值

按照正常給單元格賦值便可,只是在合併的單元格第一行賦值就行,不用重複賦值;orm

cell = row.createCell((short) 1);
cell.setCellValue(eventVO.getEventId());
cell.setCellStyle(align_center_style);

難點2:數據驗證-下拉框

在導出excel文件時,須要添加數據驗證的下拉框。如圖:
blog

代碼實現策略:

step 1:設置須要進行數據驗證的單元格範圍和可供選擇的值

/**
     * 設置 excel數據驗證
     * 
     * @param firstRow
     * @param firstCol
     * @param endRow
     * @param endCol
     * @param strList  可供選擇的值
     * @return
     * @since @ 2018年3月14日
     */
    XSSFDataValidation getDataValidationList(XSSFSheet sheet, short firstRow, short firstCol, short endRow, short endCol, List<String> strList) {
        String[] datas = strList.toArray(new String[0]);
        XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
        XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint) dvHelper
                .createExplicitListConstraint(datas);
        CellRangeAddressList addressList = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
        XSSFDataValidation validation = (XSSFDataValidation) dvHelper.createValidation(dvConstraint, addressList);
        return validation;
    }

step 2:給當前sheet添加數據驗證

sheet.addValidationData(line2ValidationList);

難點3:數據驗證-某列保證惟一性

有時候在excel文件的某列添加數據時,須要保證某列的數據惟一。這就須要使用excel的數據驗證-自定義,設置爲:=COUNTIF($B$2:B2,B2)=1(說明:從B2開始,B列的數據保證惟一,如果重複會給出提示,不能保存)
ci

代碼實現策略:

step 1:設置須要進行數據驗證的單元格範圍

public static XSSFDataValidation getDataValidationCustomFormula(XSSFSheet sheet, short firstRow, short firstCol, short endRow, short endCol, String formula) {
        XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
        XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint) dvHelper
                .createCustomConstraint(formula);
        CellRangeAddressList addressList = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
        XSSFDataValidation validation = (XSSFDataValidation) dvHelper.createValidation(dvConstraint, addressList);

        validation.createErrorBox("Error", "Repeating Date.");
        validation.setShowErrorBox(true);
        validation.setEmptyCellAllowed(true);
        validation.setSuppressDropDownArrow(true);
        validation.setShowPromptBox(true);
        validation.setErrorStyle(DataValidation.ErrorStyle.STOP);

        return validation;
    }

step 2:給當前sheet添加數據驗證

XSSFDataValidation dataValidation = XX.getDataValidationCustomFormula((XSSFSheet) eventSheet, (short) 1, (short) 1, (short) (lineNum + 5), (short) 1, "=COUNTIF($B$2:B2,B2)=1");
    if (dataValidation != null) {
        eventSheet.addValidationData(dataValidation);
    }
相關文章
相關標籤/搜索