导出Excel

1、引入依赖

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.monitorjbl</groupId>
            <artifactId>xlsx-streamer</artifactId>
            <version>2.1.0</version>
        </dependency>

2、编写ExcelDataDO类

@Data
public class ExcelDataDO<T> {
    public Class<T> clazz;

    public ExcelData(Class<T> clazz) {
        this.clazz = clazz;
    }

    public String sheetName;
    public List<T> data;
}

3、编写自动封装@ExcelField注解类

@Retention(RetentionPolicy.RUNTIME)
@Target({java.lang.annotation.ElementType.FIELD})
public @interface ExcelField {

    /**
     * 导出到Excel中的名字.
     */
    public abstract String name();


    /**
     * 配置列的名称,对应A,B,C,D....
     */
    public abstract String column();


    /**
     * 必填项
     */
    public abstract boolean required() default false;

    /**
     * 校验规则(正则)
     */
    public abstract String regex() default "";

    /**
     * 是否导出数据
     */
    public abstract boolean isExport() default true;
}

4、编写自动封装@ExcelHeaderField注解类

@Retention(RetentionPolicy.RUNTIME)
@Target({java.lang.annotation.ElementType.FIELD})
public @interface ExcelHeaderField {

    /**
     * 导出到Excel中的名字.
     */

    public abstract String name();


    /**
     * 配置列的名称,对应A,B,C,D....
     */

    public abstract String column();

    /**
     * 配置所在行索引
     */
    public abstract int row();


    /**
     * 配置所在行合
     */
    public abstract String rowMerge() default "";

    /**
     * 是否导出数据
     */
    public abstract boolean isExport() default true;
}

5、编写自动封装ExcelChannerDO实体类

@Data
public class ExcelChannerDO{

    private int sheetIndex = 0;
    private int headRow = 2;
    @ExcelHeaderField(name = "附表2-4:XX市建制村通达路径表", column = "A", row = 1, rowMerge = "N")
    private String fileName="附表2-4:XX市建制村通达路径表";
    /**
     * 序号
     */
    @ExcelField(name = "序号", column = "A", required = true)
    @ExcelHeaderField(name = "序号", column = "A", row = 2)
    private String serialNo;
    /**
     * 村编码
     */
    @ExcelField(name = "村名称", column = "B", required = true)
    @ExcelHeaderField(name = "村名称", column = "B", row = 2)
    private String countryCode;

    /**
     * 村名称
     */
    @ExcelField(name = "村名称", column = "C", required = true)
    @ExcelHeaderField(name = "村名称", column = "C", row = 2)
    private String countryName;
    /**
     * 路径序号
     */
    @ExcelField(name = "路径序号", column = "D", required = true)
    @ExcelHeaderField(name = "路径序号", column = "D", row = 2)
    private String roadSerialNo;
    /**
     * 路径中路线名称
     */
    @ExcelField(name = "路线名称", column = "E", required = true)
    @ExcelHeaderField(name = "路线名称", column = "E", row = 2)
    private String roadName;
    /**
     * 路径中路线代码
     */
    @ExcelField(name = "路线代码", column = "F", required = true)
    @ExcelHeaderField(name = "路线代码", column = "F", row = 2)
    private String roadCode;
    /**
     * 基础路线id
     */
    private String basicRoadId;
    /**
     * 路线在路径中的起点桩号
     */
    @ExcelField(name = "路线在路径中的起点桩号", column = "G", required = true)
    @ExcelHeaderField(name = "路线在路径中的起点桩号", column = "G", row = 2)
    private BigDecimal startPointSectionNo;
    /**
     * 路线在路径中的止点桩号
     */
    @ExcelField(name = "路线在路径中的止点桩号", column = "H", required = true)
    @ExcelHeaderField(name = "路线在路径中的止点桩号", column = "H", row = 2)
    private BigDecimal endPointSectionNo;
    /**
     * 技术等级
     */
    @ExcelField(name = "技术等级", column = "J", required = true)
    @ExcelHeaderField(name = "技术等级", column = "J", row = 2)
    private String technicalGrade;
    /**
     * 市编码
     */
    private String cityCode;

    /**
     * 市名称
     */
    @ExcelField(name = "市名称", column = "K", required = true)
    @ExcelHeaderField(name = "市名称", column = "K", row = 2)
    private String cityName;

    /**
     * 县编码
     */
    private String countyCode;

    /**
     * 县名称
     */
    @ExcelField(name = "县名称", column = "L", required = true)
    @ExcelHeaderField(name = "县名称", column = "L", row = 2)
    private String countyName;/**
     * 乡镇编码
     */
    private String villageCode;
    /**
     * 乡镇名称
     */
    @ExcelField(name = "乡镇名称", column = "M", required = true)
    @ExcelHeaderField(name = "乡镇名称", column = "M", row = 2)
    private String villageName;
    /**
     * 备注
     */
    @ExcelField(name = "备注", column = "N", required = true)
    @ExcelHeaderField(name = "备注", column = "N", row = 2)
    private String remark;
}

6、编写ExcelUtil类

/**
 * Excel 工具类.
 */
@SuppressWarnings("all")
public class ExcelUtil<T> {
    public Class<T> clazz;
    boolean v2007 = true;

    private Workbook workbook;

    public ExcelUtil(Class<T> clazz) {
        this.clazz = clazz;
    }

    public Workbook getWorkbook(InputStream in, boolean v2007) throws Exception {
        Workbook workbook = null;
        this.v2007 = v2007;
        if (v2007) {
            workbook = StreamingReader.builder().rowCacheSize(1000).bufferSize(4096).open(in);
        } else {
            workbook = new HSSFWorkbook(in);
        }
        return workbook;
    }

    public boolean validity(Workbook workbook) throws Exception {
        Sheet sheet = workbook.getSheetAt(0);
        List<Field> allFields = getMappedFiled(clazz, null);
        if (sheet.getLastRowNum() <= 0) {
            return false;
        }
        Row topRow = null;
        boolean flag = false;
        for (Row row : sheet) {
            if (flag) {
                break;
            }
            topRow = row;
            flag = true;
        }
        int colNum = 0;
        for (Field field : allFields) {
            if (field.isAnnotationPresent(ExcelField.class)) {
                ExcelField attr = field.getAnnotation(ExcelField.class);
                if (topRow.getCell(colNum) == null) {

                    return false;
                } else {
                    String headName = topRow.getCell(colNum).getStringCellValue();
                    if (!headName.equals(attr.name())) {
                        return false;
                    }
                }
                colNum++;

            }
        }
        return true;
    }


    public List<ExcelDataDO<T>> getList(Workbook workbook, int headRow) throws Exception {
        List<ExcelDataDO<T>> result = new ArrayList<ExcelDataDO<T>>();
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            Sheet sheet = workbook.getSheetAt(i);
            ExcelDataDO<T> exceData = new ExcelDataDO<T>(clazz);
            List<T> list = getList(sheet, headRow);
            exceData.setSheetName(sheet.getSheetName());
            exceData.setData(list);
            result.add(exceData);
        }
        return result;
    }

    public List<ExcelDataDO<T>> getList(Workbook workbook, int sheetIndex, int headRow) throws Exception {
        List<ExcelDataDO<T>> result = new ArrayList<ExcelDataDO<T>>();
        Sheet sheet = workbook.getSheetAt(sheetIndex);
        ExcelDataDO<T> exceData = new ExcelDataDO<T>(clazz);
        List<T> list = getList(sheet, headRow);
        exceData.setSheetName(sheet.getSheetName());
        exceData.setData(list);
        result.add(exceData);
        return result;
    }

    public List<T> getList(Sheet sheet, int headRow) throws Exception {
        List<T> list = new ArrayList<>();
        int maxCol = 0;
        List<Field> allFields = getMappedFiled(clazz, null);
        Map<Integer, Field> fieldsMap = new HashMap<>();
        for (Field field : allFields) {
            if (field.isAnnotationPresent(ExcelField.class)) {
                ExcelField attr = field.getAnnotation(ExcelField.class);
                int col = getExcelCol(attr.column());
                maxCol = Math.max(col, maxCol);
                field.setAccessible(true);
                fieldsMap.put(col, field);
            }
        }
        int index = 0;
        boolean flag = false;
        for (Row row : sheet) {
            int cellNum = maxCol;
            index = index + 1;
            if (index <= headRow) {
                continue;
            }
            System.out.println(row.getCell(0));
//            System.out.println(row.getCell(0).getStringCellValue());
            /*if (row.getCell(0).getStringCellValue().equals("1") || flag) {
                flag = true;
            } else {
                continue;
            }*/
           /* if (row.getCell(0).getStringCellValue().equals("沈阳市") || flag) {
                flag = true;
            } else {
                continue;
            }*/
            T entity = null;
            for (int j = 0; j <= cellNum; j++) {
                Cell cell = row.getCell(j);
                if (cell == null) {
                    continue;
                }
                if (!v2007) {
                    cell.setCellType(CellType.STRING);
                }
                String c = cell.getStringCellValue();
                if (c == null || c.equals("")) {
                    continue;
                }
                entity = (entity == null ? clazz.newInstance() : entity);

                Field field = fieldsMap.get(j);
                if (field == null) {
                    continue;
                }
                Class<?> fieldType = field.getType();
                if (String.class == fieldType) {
                    field.set(entity, String.valueOf(c));
                } else if ((Integer.TYPE == fieldType)
                        || (Integer.class == fieldType)) {
                    field.set(entity, Integer.parseInt(c));
                } else if ((Long.TYPE == fieldType)
                        || (Long.class == fieldType)) {
                    field.set(entity, Long.valueOf(c));
                } else if ((Float.TYPE == fieldType)
                        || (Float.class == fieldType)) {
                    field.set(entity, Float.valueOf(c));
                } else if ((Short.TYPE == fieldType)
                        || (Short.class == fieldType)) {
                    field.set(entity, Short.valueOf(c));
                } else if ((Double.TYPE == fieldType)
                        || (Double.class == fieldType)) {
                    field.set(entity, Double.valueOf(c));
                } else if ((BigDecimal.class == fieldType)
                        || (BigDecimal.class == fieldType)) {
                    c = c.replaceAll("\\\\(.*?\\\\)", "");
                    field.set(entity, new BigDecimal(c));
                } else if (Character.TYPE == fieldType) {
                    if ((c != null) && (c.length() > 0)) {
                        field.set(entity, Character.valueOf(c.charAt(0)));
                    }
                }
            }
            if (entity != null) {
                list.add(entity);
            }
            /*if (!flag) {
                throw new Exception("未找到有效数据.");
            }*/
        }
        return list;
    }

    public int getExcelCol(String col) {
        col = col.toUpperCase();
        int count = -1;
        char[] cs = col.toCharArray();
        for (int i = 0; i < cs.length; i++) {
            count += (cs[i] - 64) * Math.pow(26, cs.length - 1 - i);
        }
        return count;
    }

    public int getExcelRow(int row) {
        return row -1;
    }

    public Sheet setHeaders(String sheetName) throws IllegalAccessException, InstantiationException {
        Sheet sheet = this.workbook.getSheet(sheetName);
        int maxCol = 0;
        List<Field> allFields = getMappedFiled(clazz, null);
        Map<Integer, Map<Integer, Field>> excelMap = new HashMap<>();
        for (Field field : allFields) {
            if (field.isAnnotationPresent(ExcelHeaderField.class)) {
                ExcelHeaderField attr = field.getAnnotation(ExcelHeaderField.class);
                int col = getExcelCol(attr.column());
                int row = getExcelRow(attr.row());
                Map<Integer, Field> fieldsMap = null;
                if (excelMap.containsKey(row)) {
                    fieldsMap = excelMap.get(row);
                } else {
                    fieldsMap = new HashMap<>();
                }
                maxCol = Math.max(col, maxCol);
                field.setAccessible(true);
                fieldsMap.put(col, field);
                excelMap.put(row, fieldsMap);
            }
        }
        for (int rowIndex : excelMap.keySet()) {
            Row row = sheet.createRow(rowIndex);
            Map<Integer, Field> fieldsMap = excelMap.get(rowIndex);
            for (int cellIndex : fieldsMap.keySet()) {
                Cell cell = row.createCell(cellIndex);
                Field field = fieldsMap.get(cellIndex);
                ExcelHeaderField attr = field.getAnnotation(ExcelHeaderField.class);
                cell.setCellValue(attr.name());
                int rowMerge = StringUtils.isNotEmpty(attr.rowMerge()) ? getExcelCol(attr.rowMerge()) : cellIndex;
                int lineMerge = this.lineMerge(rowIndex, cellIndex, excelMap);
                if (lineMerge != rowIndex || rowMerge != cellIndex) {
                    sheet.addMergedRegion(new CellRangeAddress(rowIndex, lineMerge , cellIndex, rowMerge));
                }
            }
        }
        return sheet;
    }


    public void writeData(Sheet sheet, List<ExcelDataBaseDO> list, int headRow) throws Exception {
        List<Field> allAnnoFields = getMappedFiled(clazz, null);
        Map<Integer, Field> fieldsMap = new HashMap<>();
        int maxCol = 0;
        for (Field field : allAnnoFields) {
            if (field.isAnnotationPresent(ExcelField.class)) {
                ExcelField attr = field.getAnnotation(ExcelField.class);
                int col = getExcelCol(attr.column());
                maxCol = Math.max(col, maxCol);
                field.setAccessible(true);
                fieldsMap.put(col, field);
            }
        }
        int num = 0;
        for (ExcelDataBaseDO excelDataBaseDO : list){
            Row row = sheet.createRow(num + headRow);
            if (excelDataBaseDO != null){
                for (int cellIndex : fieldsMap.keySet()) {
                    Field field = fieldsMap.get(cellIndex);
                    Object o = field.get(excelDataBaseDO);
                    row.createCell(cellIndex).setCellValue(String.valueOf(field.get(excelDataBaseDO)));
                }
            }
            num++;
        }
        System.out.println(headRow);
    }

    public void writeData(String sheetName,List<ExcelDataBaseDO> list) throws Exception {
//        HSSFSheet sheet,
        Sheet sheet = this.workbook.getSheet(sheetName);
        Field[] fields = clazz.getDeclaredFields();
        int headRow = 0;
        Object object = clazz.newInstance();
        for (Field field : fields) {
            if ("headRow".equals(field.getName())) {
                field.setAccessible(true);
                Object o = field.get(object);
                headRow = Integer.valueOf(String.valueOf(field.get(object)));
            }
        }
        this.writeData(sheet,list,headRow);
    }


    //  导出excel   单个sheet页
    public HSSFWorkbook exportExcel(HSSFSheet sheet, List<ExcelDataBaseDO> list, String name) throws Exception {
        // 创建一个Workbook
        HSSFWorkbook workbook = new HSSFWorkbook();
//        sheet = this.setHeaders(workbook.createSheet(), name);
//        writeData(sheet, list);
        return workbook;
    }

    //  创建工作目录
    public Workbook createExcel(String... sheetArr) throws Exception {
        // 创建一个Workbook
        Workbook workbook = new HSSFWorkbook();
        for (int i = 0; i < sheetArr.length; i++) {
            Sheet sheet = workbook.createSheet(sheetArr[i]);
        }
        this.workbook = workbook;
        return workbook;
    }


    private List<Field> getMappedFiled(Class clazz, List<Field> fields) {
        if (fields == null) {
            fields = new ArrayList<>();
        }

        Field[] allFields = clazz.getDeclaredFields();
        for (Field field : allFields) {
            if (field.isAnnotationPresent(ExcelField.class) || field.isAnnotationPresent(ExcelHeaderField.class)) {
                fields.add(field);
            }
        }

        if (clazz.getSuperclass() != null && !clazz.getSuperclass().equals(Object.class)) {
            getMappedFiled(clazz.getSuperclass(), fields);
        }
        return fields;

    }

    private boolean notEmpty(Object object) {
        if (object == null || String.valueOf(object).trim().equals("")) {
            return false;
        }
        return true;
    }


    private int lineMerge(int row, int cell, Map<Integer, Map<Integer, Field>> excelMap){
        int lineMerge = row;
        boolean flag = true;
        for (int rowIndex : excelMap.keySet()) {
            if (row < rowIndex) {
                Map<Integer, Field> fieldsMap = excelMap.get(rowIndex);
                if (!fieldsMap.containsKey(cell)) {
                    lineMerge = rowIndex;
                } else {
                    lineMerge = fieldsMap.get(cell).getAnnotation(ExcelHeaderField.class).row() - 1 - 1;
                    break;
                }
            }
        }
        return lineMerge;
    }


    private boolean match(String regex, String str) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        return matcher.matches();
    }

    public static boolean isChartNum(String str) {
        String[] array = {"一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"};
        return Arrays.asList(array).contains(str);
    }
    
}
接口测试
    //  创建一个workbook
            Workbook workbook = excelUtil.createExcel("sheet1");
            excelUtil.setHeaders("sheet1");
            excelUtil.writeData("sheet1", result);
            OutputStream output=response.getOutputStream();
            response.reset();
            response.setHeader("Access-Control-Expose-Headers", "content-disposition");
            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(excelDataBaseDO.getFileName(), "UTF-8").replace("+","%20"));
            response.setContentType("application/octet-stream;charset:utf-8");
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            workbook.write(output);
            output.flush();
            output.close();
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,591评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,448评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,823评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,204评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,228评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,190评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,078评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,923评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,334评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,550评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,727评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,428评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,022评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,672评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,826评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,734评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,619评论 2 354

推荐阅读更多精彩内容