自定義註解實現Excel的解析生成

1.自定義註解

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Created by weili on 2017/7/24.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.TYPE})
public @interface ExcelAttribute {

    /**
     * excel裏的sheet名,默認是"sheet1"
     * @return
     */
    String sheetName() default "sheet1";
    /**
     * excel裏對應的列名,默認爲""
     * @return
     */
    String columnName() default "";
    /**
     * 列對應的排序序號,默認是0
     * @return
     */
    int order() default 0;

    enum DataType {
        String, Number, Date
    }
    /**
     * 數據類型,可以是String,Number(數字型),Date等類型
     * @return
     */
    DataType type() default DataType.String;
    /**
     * 日期格式,默認是"yyyy-MM-dd HH:mm:ss"
     * @return
     */
    String datePattern() default "yyyyMMdd HH:mm:ss";
    /**
     * 保留小數點後的位數,默認是0
     * @return
     */
    int decimalNums() default 0;
    /**
     * 背景顏色,默認爲白色"FFFFFF",
     * 表示形式爲顏色的十六進制字符串,常見的:
     * red: "FF0000",Orange: "FFA500",yellow: "FFFF00",
     * green: "008000",blue: "0000FF",purple: "800080"
     * @return
     */
    String fillColor() default "FFFFFF";
    /**
     * 字段是否放棄存儲到excel裏,默認爲false
     * @return
     */
    boolean skip() default false;
}
2.生成excel的工具類

import com.creditease.microloan.mil.tasks.common.annotation.ExcelAttribute;
import com.creditease.microloan.mil.tasks.exceptions.BusinessRuntimeException;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.awt.Color;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

/**
 * Created byweili on 2017/7/20.
 */
@Component
public class ExcelUtil<T> {

    /**
     * 根據filePath和dataset創建文件
     * @param filePath
     * @param dataset
     * @param <T>
     */
    public static <T> void createFile(String filePath, List<T> dataset) {
        SXSSFWorkbook wb = new SXSSFWorkbook();
        createExcel( wb, dataset);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filePath);
            wb.write(out);
        }
        catch (Exception e){
            throw new BusinessRuntimeException("文件創建失敗!",e);
        }
        finally {
            if(out!=null) {
                try {
                    out.close();
                }
                catch (Exception e){
                    throw new BusinessRuntimeException("關閉文件輸出流失敗!",e);
                }
            }

        }

    }

    /**
     * 創建sheet,並添加數據到裏面
     * @param wb
     * @param dataset
     * @param <T>
     */
    private static <T> void createExcel(SXSSFWorkbook wb, List<T> dataset ) {
        if(CollectionUtils.isEmpty(dataset) ) {
            return;
        }
        T t = dataset.get(0);
        // 獲取實體類的所有屬性,即包括public、private和proteced,但是不包括父類的申明字段
        //  一個field表示一個屬性
        Field[] fields = t.getClass().getDeclaredFields();
        // 整個類的註解,得到了定義的sheetName
        ExcelAttribute classAttribute = t.getClass().getAnnotation(ExcelAttribute.class);
        SXSSFSheet sheet = wb.createSheet(classAttribute.sheetName());

        // excel裏存儲類的部分屬性和順序號
        Map<Field,Integer> map = new LinkedHashMap<>();
        ExcelAttribute excelAttribute = null;
        for (Field field : fields) {
            // 某個屬性上的註解,如果沒寫註解或者註解裏的skip爲true,表示該列不會存儲到excel裏
            excelAttribute = field.getAnnotation(ExcelAttribute.class);
            if (excelAttribute != null) {
                if (!excelAttribute.skip()) {
                    map.put(field, excelAttribute.order());
                }
            }
        }
        //  排序
        List<Map.Entry<Field,Integer>> list = new ArrayList<Map.Entry<Field,Integer>>(map.entrySet());
        Collections.sort(list, (o1, o2) -> o1.getValue().compareTo(o2.getValue()));

        // 存儲類的註解skip爲false的排序後的屬性對應的Field
        List<Field> excelFields = new ArrayList<>();
        for(Map.Entry<Field,Integer> mapping:list){
            excelFields.add(mapping.getKey());
        }
        // excel裏存儲的列的ExcelAttribute
        List<ExcelAttribute> attributes = new ArrayList<>();
        for (int j = 0; j < excelFields.size(); j++) {
            attributes.add(excelFields.get(j).getAnnotation(ExcelAttribute.class));
        }
        addDataToExcel(wb,dataset,excelFields, attributes,sheet);

        // 自動調整列寬
        sheet.trackAllColumnsForAutoSizing();
        for(int i=0;i<excelFields.size();i++) {
            sheet.autoSizeColumn(i);
        }

    }

    /**
     * 添加數據到excel中
     * @param wb
     * @param dataset
     * @param excelFields
     * @param attributes
     * @param sheet
     * @param <T>
     */
    private static <T> void addDataToExcel(SXSSFWorkbook wb, List<T> dataset,List<Field> excelFields, List<ExcelAttribute> attributes,Sheet sheet) {
        XSSFCellStyle style = (XSSFCellStyle)wb.createCellStyle();
        // 居中
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);

        // excel放入第一行列的名稱
        Row row = sheet.createRow(0);
        for (int j = 0; j < excelFields.size(); j++) {
            Cell cell = row.createCell(j);
            ExcelAttribute oneAttribute = attributes.get(j);
            cell.setCellValue(oneAttribute.columnName());
            cell.setCellStyle(style);
        }
        // 添加數據到excel
        for(int i=0;i<dataset.size();i++) {
            // 數據行號從1開始,因爲第0行放的是列的名稱
            row = sheet.createRow(i+1);
            for(int j=0;j<attributes.size();j++) {
                Cell cell = row.createCell(j);
                ExcelAttribute oneAttribute = attributes.get(j);

                style = (XSSFCellStyle)wb.createCellStyle();
                // 居中
                style.setAlignment(HorizontalAlignment.CENTER);
                style.setVerticalAlignment(VerticalAlignment.CENTER);
                // 填充色
                XSSFColor myColor = new XSSFColor(toColorFromString(oneAttribute.fillColor()));
                style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                style.setFillForegroundColor(myColor);
                // 四個邊框
                style.setBorderBottom(BorderStyle.THIN);
                style.setBorderLeft(BorderStyle.THIN);
                style.setBorderRight(BorderStyle.THIN);
                style.setBorderTop(BorderStyle.THIN);
                cell.setCellStyle(style);
                try{
                    // 根據屬性名獲取屬性值
                    String cellValue = BeanUtils.getProperty( dataset.get(i), excelFields.get(j).getName());
                    if(ExcelAttribute.DataType.Date.equals(oneAttribute.type()))
                    {
                        // CST格式的時間字符串轉爲Date對象
                        String CST_FORMAT = "EEE MMM dd HH:mm:ss z yyyy";
                        Date cstDate = new SimpleDateFormat(CST_FORMAT, Locale.US).parse(cellValue);
                        DateFormat df = new SimpleDateFormat(
                                oneAttribute.datePattern());
                        cell.setCellValue( df.format(cstDate) );
                    }
                    else if(ExcelAttribute.DataType.Number.equals(oneAttribute.type())) {
                        // 保留小數點後的位數
                        int decimalNums = oneAttribute.decimalNums();
                        StringBuilder format = new StringBuilder("#0");
                        for(int w=0;w<decimalNums;w++) {
                            if(w==0) {
                                format.append(".");
                            }
                            format.append("0");
                        }
                        cell.setCellValue(String.valueOf(new DecimalFormat(format.toString()).format(Double.parseDouble(cellValue))));
                    }
                    else {
                        cell.setCellValue(cellValue);
                    }
                }
                catch (Exception e) {
                    throw new BusinessRuntimeException("獲取類的屬性值失敗!", e);
                }

            }
        }

    }

    /**
     * 顏色的16進制字符串轉換成Color對象
     * @param colorStr 例如藍色爲"0000FF"
     * @return Color對象
     * */
    private static Color toColorFromString(String colorStr){
        Color color =  new Color(Integer.parseInt(colorStr, 16)) ;
        return color;
    }

}
3.被註解的實體類

import com.creditease.microloan.mil.tasks.common.annotation.ExcelAttribute;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.Date;

/**
 * Created by weili on 2017/7/20.
 */
@Data
@AllArgsConstructor
@ExcelAttribute(sheetName = "stuSheet")
public class Stu {

    @ExcelAttribute(columnName="學號",order=0,fillColor = "FF0000")
    private Integer stuNo;
    @ExcelAttribute(columnName="姓名",order=2,skip = true)
    private String name;
    @ExcelAttribute(columnName="成績",order=5, type = ExcelAttribute.DataType.Number,decimalNums = 4)
    private Double grade;
    @ExcelAttribute(columnName="註冊時間",order=0,datePattern = "yyyy-MM-dd HH:mm",type = ExcelAttribute.DataType.Date)
    private Date loginDate;
    @ExcelAttribute(columnName="是否男孩",order=4,fillColor = "FFFF00")
    private Boolean isBoy;
}


4.測試

package com.creditease.microloan.mil.tasks;

import com.creditease.microloan.mil.tasks.model.Stu;
import com.creditease.microloan.mil.tasks.util.ExcelUtil;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by weili on 2017/7/20.
 */
public class ExcelUtilTest {

    @Test
    public void test() {
        List<Stu> dataset = new ArrayList<>();
        dataset.add(new Stu(1,"zhangsan",67.9990,new Date(),true));
        dataset.add(new Stu(2,"lisi",0.03,new Date(),false));
        String[] fieldColumns ={"number","sname"};
        String sheetName ="ss33";
        String path = "/Users/apple/Desktop/11.xlsx";
        ExcelUtil.createFile(path,dataset);
    }


}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章