栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

目录
    • 一、导出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;
    
    @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;
    
    @Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface ExcelField {
        
        String value() default "";
    
        
        String title();
    
        
        int type() default 0;
    
        
        int align() default 0;
    
        
        int sort() default 0;
    
        
        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;
    
    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);
    
        
        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;
        }
    
        
        public static void invokeSetter(Object obj, String propertyName, Object value) {
            Object object = obj;
            String[] names = StringUtils.split(propertyName, ".");
            for (int i=0; i[] parameterTypes,
                                          final Object[] args) {
            Method method = getAccessibleMethod(obj, methodName, parameterTypes);
            if (method == null) {
                throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]");
            }
    
            try {
                return method.invoke(obj, args);
            } catch (Exception e) {
                throw convertReflectionExceptionToUnchecked(e);
            }
        }
    
        
        public static Object invokeMethodByName(final Object obj, final String methodName, final Object[] args) {
            Method method = getAccessibleMethodByName(obj, methodName);
            if (method == null) {
                throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]");
            }
    
            try {
                return method.invoke(obj, args);
            } catch (Exception e) {
                throw convertReflectionExceptionToUnchecked(e);
            }
        }
    
        
        public static Field getAccessibleField(final Object obj, final String fieldName) {
            Validate.notNull(obj, "object can't be null");
            Validate.notBlank(fieldName, "fieldName can't be blank");
            for (Class superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
                try {
                    Field field = superClass.getDeclaredField(fieldName);
                    makeAccessible(field);
                    return field;
                } catch (NoSuchFieldException e) {//NOSONAR
                    // Field不在当前类定义,继续向上转型
                    continue;// new add
                }
            }
            return null;
        }
    
        
        public static Method getAccessibleMethod(final Object obj, final String methodName,
                                                 final Class... parameterTypes) {
            Validate.notNull(obj, "object can't be null");
            Validate.notBlank(methodName, "methodName can't be blank");
    
            for (Class searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {
                try {
                    Method method = searchType.getDeclaredMethod(methodName, parameterTypes);
                    makeAccessible(method);
                    return method;
                } catch (NoSuchMethodException e) {
                    // Method不在当前类定义,继续向上转型
                    continue;// new add
                }
            }
            return null;
        }
    
        
        public static Method getAccessibleMethodByName(final Object obj, final String methodName) {
            Validate.notNull(obj, "object can't be null");
            Validate.notBlank(methodName, "methodName can't be blank");
    
            for (Class searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {
                Method[] methods = searchType.getDeclaredMethods();
                for (Method method : methods) {
                    if (method.getName().equals(methodName)) {
                        makeAccessible(method);
                        return method;
                    }
                }
            }
            return null;
        }
    
        
        public static void makeAccessible(Method method) {
            if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
                    && !method.isAccessible()) {
                method.setAccessible(true);
            }
        }
    
        
        public static void makeAccessible(Field field) {
            if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()) || Modifier
                    .isFinal(field.getModifiers())) && !field.isAccessible()) {
                field.setAccessible(true);
            }
        }
    
        
        @SuppressWarnings("unchecked")
        public static  Class getClassGenricType(final Class clazz) {
            return getClassGenricType(clazz, 0);
        }
    
        
        public static Class getClassGenricType(final Class clazz, final int index) {
    
            Type genType = clazz.getGenericSuperclass();
    
            if (!(genType instanceof ParameterizedType)) {
                logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
                return Object.class;
            }
    
            Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
    
            if (index >= params.length || index < 0) {
                logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
                        + params.length);
                return Object.class;
            }
            if (!(params[index] instanceof Class)) {
                logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
                return Object.class;
            }
    
            return (Class) params[index];
        }
    
        public static Class getUserClass(Object instance) {
            Assert.notNull(instance, "Instance must not be null");
            Class clazz = instance.getClass();
            if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) {
                Class superClass = clazz.getSuperclass();
                if (superClass != null && !Object.class.equals(superClass)) {
                    return superClass;
                }
            }
            return clazz;
    
        }
    
        
        public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) {
            if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException
                    || e instanceof NoSuchMethodException) {
                return new IllegalArgumentException(e);
            } else if (e instanceof InvocationTargetException) {
                return new RuntimeException(((InvocationTargetException) e).getTargetException());
            } else if (e instanceof RuntimeException) {
                return (RuntimeException) e;
            }
            return new RuntimeException("Unexpected Checked Exception.", e);
        }
    }
    

    (4)、导出Excel文件工具类

    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.lang.reflect.Field;
    import java.lang.reflect.Method;
    import java.net.URLEncoder;
    import java.util.*;
    import javax.servlet.http.HttpServletResponse;
    import org.apache.commons.lang.StringUtils;
    import org.apache.poi.ss.usermodel.*;
    import org.apache.poi.ss.util.CellRangeAddress;
    import org.apache.poi.xssf.streaming.SXSSFWorkbook;
    import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
    import org.apache.poi.xssf.usermodel.XSSFRichTextString;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import com.google.common.collect.Lists;
    
    public class ExportExcel {
        private static Logger log = LoggerFactory.getLogger(ExportExcel.class);
        
        private SXSSFWorkbook wb;
    
        
        private Sheet sheet;
    
        
        private Map styles;
    
        
        private int rownum;
    
        
        List annotationList = Lists.newArrayList();
    
        
        public ExportExcel(String title, Class cls){
            this(title, cls, 1);
        }
    
        
        public ExportExcel(String title, Class cls, int type, int... groups){
            // Get annotation field
            Field[] fs = cls.getDeclaredFields();
            for (Field f : fs){
                ExcelField ef = f.getAnnotation(ExcelField.class);
                if (ef != null && (ef.type()==0 || ef.type()==type)){
                    if (groups!=null && groups.length>0){
                        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, f});
                                    break;
                                }
                            }
                        }
                    }else{
                        annotationList.add(new Object[]{ef, f});
                    }
                }
            }
            // Get annotation method
            Method[] ms = cls.getDeclaredMethods();
            for (Method m : ms){
                ExcelField ef = m.getAnnotation(ExcelField.class);
                if (ef != null && (ef.type()==0 || ef.type()==type)){
                    if (groups!=null && groups.length>0){
                        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);
        }
    
        
        public ExportExcel(String title, String[] headers) {
            initialize(title, Lists.newArrayList(headers));
        }
    
        
        public ExportExcel(String title, List headerList) {
            initialize(title, 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 < headerList.size(); i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellStyle(styles.get("header"));
                String[] ss = StringUtils.split(headerList.get(i), "**", 2);
                if (ss.length==2){
                    cell.setCellValue(ss[0]);
                    Comment comment = this.sheet.createDrawingPatriarch().createCellComment(
                            new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6));
                    comment.setString(new XSSFRichTextString(ss[1]));
                    cell.setCellComment(comment);
                }else{
                    cell.setCellValue(headerList.get(i));
                }
                //sheet.autoSizeColumn(i);
            }
            for (int i = 0; i < headerList.size(); i++) {
                int colWidth = sheet.getColumnWidth(i)*2;
                sheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth);
            }
            log.debug("Initialize success.");
        }
    
        
        private Map createStyles(Workbook wb) {
            Map styles = new HashMap();
    
            CellStyle style = wb.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);
            style.setVerticalAlignment(VerticalAlignment.CENTER);
            Font titleFont = wb.createFont();
            titleFont.setFontName("Arial");
            titleFont.setFontHeightInPoints((short) 16);
            titleFont.setBold(true);
            style.setFont(titleFont);
            styles.put("title", style);
    
            style = wb.createCellStyle();
            style.setVerticalAlignment(VerticalAlignment.CENTER);
            style.setBorderRight(BorderStyle.THIN);
            style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
            style.setBorderLeft(BorderStyle.THIN);
            style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
            style.setBorderTop(BorderStyle.THIN);
            style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
            style.setBorderBottom(BorderStyle.THIN);
            style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
            Font dataFont = wb.createFont();
            dataFont.setFontName("Arial");
            dataFont.setFontHeightInPoints((short) 10);
            style.setFont(dataFont);
            styles.put("data", style);
    
            style = wb.createCellStyle();
            style.cloneStyleFrom(styles.get("data"));
            style.setAlignment(HorizontalAlignment.LEFT);
            styles.put("data1", style);
    
            style = wb.createCellStyle();
            style.cloneStyleFrom(styles.get("data"));
            style.setAlignment(HorizontalAlignment.CENTER);
            styles.put("data2", style);
    
            style = wb.createCellStyle();
            style.cloneStyleFrom(styles.get("data"));
            style.setAlignment(HorizontalAlignment.RIGHT);
            styles.put("data3", style);
    
            style = wb.createCellStyle();
            style.cloneStyleFrom(styles.get("data"));
    //		style.setWrapText(true);
            style.setAlignment(HorizontalAlignment.CENTER);
            style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
            style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            Font headerFont = wb.createFont();
            headerFont.setFontName("Arial");
            headerFont.setFontHeightInPoints((short) 10);
            headerFont.setBold(true);
            headerFont.setColor(IndexedColors.WHITE.getIndex());
            style.setFont(headerFont);
            styles.put("header", style);
    
            return styles;
        }
    
        
        public Row addRow(){
            return sheet.createRow(rownum++);
        }
    
    
        
        public Cell addCell(Row row, int column, Object val){
            return this.addCell(row, column, val, 1, Class.class);
        }
    
        
        public Cell addCell(Row row, int column, Object val, int align, Class fieldType){
            Cell cell = row.createCell(column);
            CellStyle style = styles.get("data"+(align>=1&&align<=3?align:""));
            try {
                if (val == null){
                    cell.setCellValue("");
                } else if (val instanceof String) {
                    cell.setCellValue((String) val);
                } else if (val instanceof Integer) {
                    cell.setCellValue((Integer) val);
                } else if (val instanceof Long) {
                    cell.setCellValue((Long) val);
                } else if (val instanceof Double) {
                    cell.setCellValue((Double) val);
                } else if (val instanceof Float) {
                    cell.setCellValue((Float) val);
                } else if (val instanceof Date) {
                    DataFormat format = wb.createDataFormat();
                    style.setDataFormat(format.getFormat("yyyy-MM-dd"));
                    cell.setCellValue((Date) val);
                } else {
                    if (fieldType != Class.class){
                        cell.setCellValue((String)fieldType.getMethod("setValue", Object.class).invoke(null, val));
                    }else{
                        cell.setCellValue((String)Class.forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(),
                                "fieldtype."+val.getClass().getSimpleName()+"Type")).getMethod("setValue", Object.class).invoke(null, val));
                    }
                }
            } catch (Exception ex) {
                log.info("Set cell value ["+row.getRowNum()+","+column+"] error: " + ex.toString());
                cell.setCellValue(val.toString());
            }
            cell.setCellStyle(style);
            return cell;
        }
    
        
        public  ExportExcel setDataList(List list){
            for (E e : list){
                int colunm = 0;
                Row row = this.addRow();
                StringBuilder sb = new StringBuilder();
                for (Object[] os : annotationList){
                    ExcelField ef = (ExcelField)os[0];
                    Object val = null;
                    // Get entity value
                    try{
                        if (StringUtils.isNotBlank(ef.value())){
                            val = Reflections.invokeGetter(e, ef.value());
                        }else{
                            if (os[1] instanceof Field){
                                val = Reflections.invokeGetter(e, ((Field)os[1]).getName());
                            }else if (os[1] instanceof Method){
                                val = Reflections.invokeMethod(e, ((Method)os[1]).getName(), new Class[] {}, new Object[] {});
                            }
                        }
                        // If is dict, get dict label
                        //if (StringUtils.isNotBlank(ef.dictType())){
                        //	val = DictUtils.getDictLabel(val==null?"":val.toString(), ef.dictType(), "");
                        //}
                    }catch(Exception ex) {
                        // Failure to ignore
                        log.info(ex.toString());
                        val = "";
                    }
                    this.addCell(row, colunm++, val, ef.align(), ef.fieldType());
                    sb.append(val + ", ");
                }
                log.debug("Write success: ["+row.getRowNum()+"] "+sb.toString());
            }
            return this;
        }
    
        
        public ExportExcel write(OutputStream os) throws IOException{
            wb.write(os);
            return this;
        }
    
        
        public ExportExcel write(HttpServletResponse response, String fileName) throws IOException{
            response.reset();
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(fileName));
            write(response.getOutputStream());
            return this;
        }
    
        
        public ExportExcel writeFile(String name) throws FileNotFoundException, IOException{
            FileOutputStream os = new FileOutputStream(name);
            this.write(os);
            return this;
        }
    
        
        public ExportExcel dispose(){
            wb.dispose();
            return this;
        }
    }
    
  • 业务逻辑部分示例代码
    (1)、controller层

    @RequestMapping("/export")
        public R exportExecl(@RequestParam Map params) throws IOException {
            String userName=(String) params.get("userName");
            UserEntity bean =new UserEntity();
            bean.setUserName(userName);
            String path="";
            String fileName = "用户信息数据";
            //数据头
            List headerList = Arrays.asList("序号","用户名","登录名","手机号","邮箱","创建时间");
            //根据接收到的用户名查询用户数据
            List list = userService.getAllUser(bean);
            if(list.size()>0){
                ExportExcel ee = new ExportExcel(fileName, headerList);
                //为每一行,每一个单元格赋值
                for (int i = 0; i < list.size(); i++) {
                    Row row = ee.addRow();
                    ee.addCell(row,0,(list.get(i)).getRownums()+"");
                    ee.addCell(row,1,(list.get(i)).getUserName());
                    ee.addCell(row,2,(list.get(i)).getLoginName());
                    ee.addCell(row,3,(list.get(i)).getPhone());
                    ee.addCell(row,4,(list.get(i)).getEmail());
                    ee.addCell(row,5,(list.get(i)).getCreateTime());
                }
                //导出路径
                fileName = fileName==""? DateUtils.dateTimeNow():fileName+DateUtils.dateTimeNow();
                path = excel.getPath()+ fileName+".xlsx";
                try {
                    ee.writeFile(path);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                ee.dispose();
            }
            //返回文件名称,从指定目录下载时需要用到此生成的excel文件名称
            return R.ok().put("fileName",fileName);
        }
    

    (2)、service层、

    List getAllUser(UserEntity bean);
    

    (3)、dao层、mappe文件lz此处省略…根据具体需求查询即可

二、从指定目录下载excel文件 1、从指定目录下载excel文件示例截图
  • 下载时弹出的下载窗口如下图:

  • 上图中点击【确定】按钮,浏览器显示下载进度及下载位置,如下图:

  • 下载成功后,保存的下载位置,如下图:

  • 进入下载位置目录,打开下载的excel文件,如下图:

2、从指定目录下载excel文件示例代码
  • controller层代码

     
    @SysLog("下载用户信息数据")
    @RequestMapping("/downloadExcel")
    public void download(HttpServletRequest request, HttpServletResponse response) {
        try {
        //此参数为前面导出excel到指定目录方法中返回的文件名称
        String fileName = request.getParameter("fileName");
        // 要下载的文件的全路径名,
        //window环境需要转换
        String filePath =excel.getPath().replace("/","\")+fileName+".xlsx";
        //linux环境路径
        //String filePath =excel.getPath()+fileName+".xlsx";
        File file = new File(filePath);
        // 获取文件名
        String filename = file.getName();
        //通过流把文件内容写入到客户端
        InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes(),"ISO-8859-1"));
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/275558.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号