- 一、导出excel到指定目录
- 1、导出excel到指定目录示例截图
- 2、导出excel到指定目录示例代码
- 二、从指定目录下载excel文件
- 1、从指定目录下载excel文件示例截图
- 2、从指定目录下载excel文件示例代码
-
导出excel到指定目录,如下图:
-
从指定目录打开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 Mapstyles; private int rownum; List -
业务逻辑部分示例代码
(1)、controller层@RequestMapping("/export") public R exportExecl(@RequestParam Mapparams) 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文件,如下图:
-
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(); } }



