Excel 导出: 自动生成Excel JAVA工具包

自己写了一个Java工具,是关于Excel导出(write)的,后续可能还会写导入(read),因为太常用,所以分享出来

先是Annotation 两个

/**
 * @author Wang Yu
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Excel {

    /**
     * @return Array of Cells's name
     */
    String[] value();
}
/**
 * @author Wang Yu
 * CreateAt 2019-10-31 14:44
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Cell {

    /**
     * @return the position of cell, start with 0
     */
    int value() default -1;

}

工具:

/**
 * @author Wang Yu
 * CreateAt 2019-10-31 15:08
 */
public class ExcelUtil {

    private static final Logger LOG = Logger.getLogger(ExcelUtil.class);

    /**
     * create XSSFWorkbook by data
     * @param sheetName sheet name
     * @param data the data
     * @param clazz should use {@link Excel}
     * @return the XSSFWorkbook Object. Should close after use!
     */
    public static  XSSFWorkbook createWorkbook(String sheetName, List data, Class clazz) {
        if (!clazz.isAnnotationPresent(Excel.class)) {
            throw new RuntimeException("Unable createWorkbook Object to excel, " +
                    "Because: Class " + clazz.getSimpleName() + " doesn't assign from Excel.class");
        }
        try {
            Excel excelAnnotation = clazz.getAnnotation(Excel.class);
            String[] cellsArray = excelAnnotation.value();
            // create Cell Header
            XSSFWorkbook wb = new XSSFWorkbook();
            XSSFSheet sheet = wb.createSheet(sheetName);
            XSSFRow headerRow = sheet.createRow(0);
            for (int i = 0; i < cellsArray.length; i++) {
                headerRow.createCell(i).setCellValue(cellsArray[i]);
            }
            // create Data Rows
            Field[] fields = clazz.getDeclaredFields();
            for (int index = 0; index < data.size(); index++) {
                T object = data.get(index);
                // create a row
                XSSFRow dataRow = sheet.createRow(index + 1);
                // for each the fields
                int fieldIndex = 0;
                for (Field field : fields) {
                    if (!field.isAnnotationPresent(Cell.class)) {
                        continue;
                    }
                    String fieldName = field.getName();
                    Cell cellAnnotation = field.getAnnotation(Cell.class);
                    int cellIndex = cellAnnotation.value();
                    if (cellIndex == -1) {
                        cellIndex = fieldIndex;
                    }
                    XSSFCell cell = dataRow.createCell(cellIndex);
                    String getter = InvokeUtil.getter(fieldName);
                    try {
                        Method getterMethod = clazz.getDeclaredMethod(getter);
                        Object fieldValue = getterMethod.invoke(object);
                        if (fieldValue == null) {
                            cell.setCellValue(Constant.EMPTY_STR);
                        } else if (field.getType().equals(String.class)) {
                            cell.setCellValue((String) fieldValue);
                        } else if (field.getType().equals(BigDecimal.class)) {
                            BigDecimal bigDecimal = (BigDecimal) fieldValue;
                            cell.setCellValue(bigDecimal.doubleValue());
                        } else if (field.getType().equals(Integer.class)) {
                            cell.setCellValue((Integer) fieldValue);
                        } else if (field.getType().equals(Long.class)) {
                            cell.setCellValue((Long) fieldValue);
                        } else if (field.getType().equals(Date.class)) {
                            Date date = (Date) fieldValue;
                            cell.setCellValue(DateFormatUtils.format(date, Constant.DATE_FORMAT));
                        } else {
                            throw new RuntimeException("Unable convert type of : " + fieldName);
                        }
                        fieldIndex++;
                    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                        LOG.error("error occurs on ExcelUtil.createWorkbook(): ", e);
                    }
                }

            } // end of for each data

            return wb;
        } catch (Exception e) {
            LOG.error("error occurs on ExcelUtil.createWorkbook() ", e);
            return null;
        }
    }
}

 

你可能感兴趣的:(Excel 导出: 自动生成Excel JAVA工具包)