java excel導出通用工具類,只關注外層

/**
 * @Description
 * @Author 
 * @date 2020.02.18 16:56
 */
public abstract class XSSFProperties {
    /**
     * 對象
     */
    protected XSSFWorkbook workBook;
    /**
     * 頭部樣式
     */
    protected XSSFCellStyle headStyle;
    /**
     * body樣式
     */
    protected XSSFCellStyle bodyStyle;
    /**
     * 默認寬度
     */
    protected final Integer defaultWidth = 23;
    /**
     * 默認高度
     */
    protected final Float defaultHeight = 23F;
    /**
     * 寬度係數
     */
    protected static final int COEFFICIENT_WITH = 256;

    /**
     * 設置主題
     *
     * @param headColor
     */
    abstract void theme(short headColor);

}

/**
 * @Descriptions Excel生成類
 * @Author 
 * @date 2020.02.18 10:46
 */
public class XSSFBuilder extends XSSFProperties {
    /***
     * 初始化數據
     */
    public XSSFBuilder() {
        workBook = new XSSFWorkbook();
        headStyle = super.workBook.createCellStyle();
        bodyStyle = super.workBook.createCellStyle();
        defaultHeadStyle();
        defaultBodyStyle();
    }

    /**
     * 設置主題顏色
     *
     * @param headColor
     * @link org.apache.poi.ss.usermodel
     */
    @Override
    public void theme(short headColor) {
        //主題
        headStyle.setFillForegroundColor(headColor);
    }

    /**
     * 一級sheet構造
     *
     * @param
     */
    @SneakyThrows
    public void construct(List param) {
    }

    /**
     * 多級sheet構造
     *
     * @param map
     */
    @SneakyThrows
    public void construct(Map<String, List<Object>> map) {
        for (String key : map.keySet()) {
            init(map.get(key));
        }
        File file = new File("/Users/xiaocai/Downloads/test1113333.xlsx");
        FileOutputStream outStream = new FileOutputStream(file);
        workBook.write(outStream);
        outStream.flush();
        outStream.close();
    }

    /**
     * 初始化數據表格
     *
     * @param param
     */
    @SneakyThrows
    private void init(List param) {
        int index = 0;
        Class<?> clazz = param.get(index).getClass();
        Assert.isTrue(clazz.isAnnotationPresent(Sheet.class), "sheet name must not be null");
        Sheet sheetAnnotation = clazz.getAnnotation(Sheet.class);

        XSSFSheet sheet = workBook.createSheet(sheetAnnotation.name());
        defaultWideHighPoints(sheetAnnotation.name());

        //構造head
        Field[] attFields = clazz.getDeclaredFields();
        XSSFRow headRow = sheet.createRow(index);

        int count = -1;
        for (int i = 0; i < attFields.length; i++) {
            Field field = attFields[i];
            if (field.isAnnotationPresent(Anno.class)) {
                XSSFCell xssfCell = headRow.createCell(++count);
                Anno anno = field.getAnnotation(Anno.class);
                xssfCell.setCellStyle(headStyle);
                xssfCell.setCellValue(anno.name());
                sheet.setColumnWidth(i, anno.width() * COEFFICIENT_WITH);
            }

            //下拉數據填充
            if (field.isAnnotationPresent(Fold.class)) {
                Fold fold = field.getAnnotation(Fold.class);
                Method method = clazz.getMethod(fold.data());
                Object o = method.invoke(clazz.newInstance());

                Object[] info = new Object[0];
                if (o instanceof String[]) {
                    info = (Object[]) o;
                } else if (o instanceof List) {
                    info = ((List) o).toArray();
                }

                XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
                XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint)
                        dvHelper.createExplicitListConstraint(Arrays.asList(info).toArray(new String[0]));

                CellRangeAddressList addressList = new CellRangeAddressList(index + 1, param.size(), i, i);
                DataValidation validation = dvHelper.createValidation(dvConstraint, addressList);
                validation.createErrorBox("輸入值有誤", "請從下拉框中選擇");
                validation.setShowErrorBox(true);
                sheet.addValidationData(validation);
            }
        }

        //構造body
        for (int i = 0; i < param.size(); i++) {
            Object t = param.get(i);
            Field[] fields = t.getClass().getDeclaredFields();
            XSSFRow xssfRow = sheet.createRow(i + 1);
            count = -1;
            for (int k = 0; k < fields.length; k++) {
                Field field = fields[k];
                field.setAccessible(true);
                Object val = field.get(t);
                if (field.isAnnotationPresent(Anno.class)) {
                    XSSFCell xssfCell = xssfRow.createCell(++count);
                    xssfCell.setCellValue(Objects.isNull(val) ? null : String.valueOf(val));
                    xssfCell.setCellStyle(bodyStyle);
                }

            }
        }
    }

    public void defaultHeadStyle() {
        //上邊框
        headStyle.setBorderTop(BorderStyle.THIN);
        //左邊框
        headStyle.setBorderLeft(BorderStyle.THIN);
        //下邊框
        headStyle.setBorderBottom(BorderStyle.THIN);
        //右邊框
        headStyle.setBorderRight(BorderStyle.THIN);
        //水平居中
        headStyle.setAlignment(HorizontalAlignment.CENTER);
        //垂直居中
        headStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        //填充
        headStyle.setFillPattern(FillPatternType.FINE_DOTS);
        //顏色
        headStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
    }

    public void defaultBodyStyle() {
        //水平居中
        bodyStyle.setAlignment(HorizontalAlignment.CENTER);
        //垂直居中
        bodyStyle.setVerticalAlignment(VerticalAlignment.CENTER);
    }

    public void defaultWideHighPoints(String sheetName) {
        XSSFSheet sheet = workBook.getSheet(sheetName);
        sheet.setDefaultColumnWidth(defaultWidth);
        sheet.setDefaultRowHeightInPoints(defaultHeight);
    }
}

相關注解

/**
 * @Description poi註解工具類 作用域字段上
 * @Author 
 * @date 2020.02.18 13:43
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE})
public @interface Anno {
    /**
     * 標題
     *
     * @return
     */
    String name() default "";

    /**
     * 參數索引位置(寬度默認23)
     */
    int width() default 23;
}
/**
 * @Description 作用域下拉框
 * @Author 
 * @date 2020.02.20 09:41
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE})
public @interface Fold {
    //下拉選擇數據
    String data() default "";
}

/**
 * @Description 作用域方法上 創建sheet
 * @Author 
 * @date 2020.02.18 19:19
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
public @interface Sheet {
    /**
     * 參數索引位置(寬度默認23)
     */
    int index() default 0;

    /**
     * 標題
     *
     * @return
     */
    String name() default "";
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章