您当前的位置: 首页 >  spring boot

小志的博客

暂无认证

  • 0浏览

    0关注

    1217博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

spring boot项目使用poi导出excel到指定目录并且从指定目录下载excel文件

小志的博客 发布时间:2021-09-28 19:29:39 ,浏览量:0

目录
    • 一、导出excel到指定目录
      • 1、导出excel到指定目录示例截图
      • 2、导出excel到指定目录示例代码
    • 二、从指定目录下载excel文件
      • 1、从指定目录下载excel文件示例截图
      • 2、从指定目录下载excel文件示例代码

一、导出excel到指定目录 1、导出excel到指定目录示例截图
  • 导出excel到指定目录,如下图:

    在这里插入图片描述

  • 从指定目录打开excel文件,如下图:

    在这里插入图片描述

2、导出excel到指定目录示例代码
  • pom文件依赖如下:

    
    
    	org.apache.poi
    	poi-ooxml
    	4.1.2
    
       
           org.apache.commons
           commons-lang3
       
    
    	org.apache.poi
    	poi
    	4.1.2
    	compile
    
    
    	org.apache.poi
    	poi-ooxml-schemas
    	4.1.2
    	compile
    
    
    	org.apache.poi
    	poi-examples
    	4.1.2
    	compile
    
    
    	org.apache.poi
    	poi-scratchpad
    	4.1.2
    	compile
    
    
  • application.yml配置文件如下:

    #excel导出路径 示例( Windows配置D:/uploadPath/)
    export:
      path: D:/uploadPath/
    
  • excel工具类如下:

    (1)、导出excel的路径位置的配置类

    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.stereotype.Component;
    /**
     * @description: excel导出的路径位置
     * @author: xz
     */
    @Component
    @ConfigurationProperties(prefix="export")
    public class Excel {
        private String path;
    
        public String getPath() {
            return path;
        }
    
        public void setPath(String path) {
            this.path = path;
        }
    }
    

    (2)、自定义Excel的注解类

    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    /**
     * @description: Excel注解定义
     * @author: xz
     */
    @Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface ExcelField {
        /**
         * 导出字段名(默认调用当前字段的“get”方法,如指定导出字段为对象,请填写“对象名.对象属性”,例:“area.name”、“office.name”)
         */
        String value() default "";
    
        /**
         * 导出字段标题(需要添加批注请用“**”分隔,标题**批注,仅对导出模板有效)
         */
        String title();
    
        /**
         * 字段类型(0:导出导入;1:仅导出;2:仅导入)
         */
        int type() default 0;
    
        /**
         * 导出字段对齐方式(0:自动;1:靠左;2:居中;3:靠右)
         */
        int align() default 0;
    
        /**
         * 导出字段字段排序(升序)
         */
        int sort() default 0;
    
        /**
         * 如果是字典类型,请设置字典的type值
         */
        String dictType() default "";
    
        /**
         * 反射类型
         */
        Class fieldType() default Class.class;
    
        /**
         * 字段归属组(根据分组导出导入)
         */
        int[] groups() default {};
    }
    

    (3)、自定义反射工具类

    import java.lang.reflect.Field;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.lang.reflect.Modifier;
    import java.lang.reflect.ParameterizedType;
    import java.lang.reflect.Type;
    import org.apache.commons.lang.StringUtils;
    import org.apache.commons.lang3.Validate;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.util.Assert;
    /**
     * @description: 反射工具类.
     * @author: xz
     */
    public class Reflections {
        private static final String SETTER_PREFIX = "set";
    
        private static final String GETTER_PREFIX = "get";
    
        private static final String CGLIB_CLASS_SEPARATOR = "$$";
    
        private static Logger logger = LoggerFactory.getLogger(Reflections.class);
    
        /**
         * 调用Getter方法.
         * 支持多级,如:对象名.对象名.方法
         */
        public static Object invokeGetter(Object obj, String propertyName) {
            Object object = obj;
            for (String name : StringUtils.split(propertyName, ".")){
                String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name);
                object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {});
            }
            return object;
        }
    
        /**
         * 调用Setter方法, 仅匹配方法名。
         * 支持多级,如:对象名.对象名.方法
         */
        public static void invokeSetter(Object obj, String propertyName, Object value) {
            Object object = obj;
            String[] names = StringUtils.split(propertyName, ".");
            for (int i=0; i0){
                        boolean inGroup = false;
                        for (int g : groups){
                            if (inGroup){
                                break;
                            }
                            for (int efg : ef.groups()){
                                if (g == efg){
                                    inGroup = true;
                                    annotationList.add(new Object[]{ef, m});
                                    break;
                                }
                            }
                        }
                    }else{
                        annotationList.add(new Object[]{ef, m});
                    }
                }
            }
            // Field sorting
            Collections.sort(annotationList, new Comparator() {
                @Override
                public int compare(Object[] o1, Object[] o2) {
                    return new Integer(((ExcelField)o1[0]).sort()).compareTo(
                            new Integer(((ExcelField)o2[0]).sort()));
                };
            });
            // Initialize
            List headerList = Lists.newArrayList();
            for (Object[] os : annotationList){
                String t = ((ExcelField)os[0]).title();
                // 如果是导出,则去掉注释
                if (type==1){
                    String[] ss = StringUtils.split(t, "**", 2);
                    if (ss.length==2){
                        t = ss[0];
                    }
                }
                headerList.add(t);
            }
            initialize(title, headerList);
        }
    
        /**
         * 构造函数
         * @param title 表格标题,传“空值”,表示无标题
         * @param headers 表头数组
         */
        public ExportExcel(String title, String[] headers) {
            initialize(title, Lists.newArrayList(headers));
        }
    
        /**
         * 构造函数
         * @param title 表格标题,传“空值”,表示无标题
         * @param headerList 表头列表
         */
        public ExportExcel(String title, List headerList) {
            initialize(title, headerList);
        }
    
        /**
         * 初始化函数
         * @param title 表格标题,传“空值”,表示无标题
         * @param headerList 表头列表
         */
        private void initialize(String title, List headerList) {
            this.wb = new SXSSFWorkbook(500);
            this.sheet = wb.createSheet("Sheet");
            this.styles = createStyles(wb);
            // Create title
            if (StringUtils.isNotBlank(title)){
                Row titleRow = sheet.createRow(rownum++);
                titleRow.setHeightInPoints(30);
                Cell titleCell = titleRow.createCell(0);
                titleCell.setCellStyle(styles.get("title"));
                titleCell.setCellValue(title);
                sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(),
                        titleRow.getRowNum(), titleRow.getRowNum(), headerList.size()-1));
            }
            // Create header
            if (headerList == null){
                throw new RuntimeException("headerList not null!");
            }
            Row headerRow = sheet.createRow(rownum++);
            headerRow.setHeightInPoints(16);
            for (int i = 0; i             
关注
打赏
1661269038
查看更多评论
0.0537s