下面代码实现所需jar包:
tomcat-embed-core-8.5.11.jar;
commons-lang3-3.0.1.jar;
commons-io-2.5.jar;
poi-3.9.jar
(下载地址:https://files.cnblogs.com/files/Big-Boss/Java%E5%AF%BC%E5%87%BAExcel%E6%96%87%E4%BB%B6%E6%89%80%E9%9C%80jar%E5%8C%85.zip)
实现代码:
import java.io.ByteArrayOutputStream; import java.lang.reflect.Field; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; /** * 导出Excel文件 * 注:考虑到文件兼容性,导出的文件为.xls格式 * @author 【】 * */ public class ExportExcelUtil { /** * 利用Java反射机制以Excel形式导出数据 * @param objLists 要导出的数据 * @param tableName 要到处数据的实体类bean路径(实体类所在src下的路径) * @param fileName 要导出的Excel文件名 * @param response * @throws Exception */ public static void exportExcel(List<Object> objLists, String tableName, String fileName, HttpServletResponse response) throws Exception { // 利用JAVA反射通过实体类名获取其对应属性(需导出的字段) Map<String, String> map = getBeanComment(tableName); List<String> keyList = new ArrayList<>(); keyList.addAll(map.keySet()); // 创建Excel工作薄 HSSFWorkbook wb = new HSSFWorkbook(); // HSSFWorkbook每张Sheet表导出的行数最多为 65535 行 // 当要导出数据大于这个数时就需要多个Sheet表 int flag = 1; for (int i = 0; i < objLists.size(); i += 65000) { // 创建Sheet表 HSSFSheet sheet = wb.createSheet("Sheet表名" + flag); List<Object> lists = new ArrayList<>(); if (objLists.size() - i > 65000) { lists = objLists.subList(i, i + 10); } else { if (objLists.size() > i) { lists = objLists.subList(i, objLists.size()); } } // 定义表头,创建行 HSSFRow row = sheet.createRow(0); // 单元格样式 HSSFCellStyle style= wb.createCellStyle(); // 水平居中 style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建单元格 HSSFCell cell = null; int j = 0; for (String key : keyList) { cell = row.createCell(i); cell.setCellValue(map.get(key)); cell.setCellStyle(style); j++; } for (int k = 0; k < lists.size(); k++) { // 利用java反射机制获取该类的所有字段信息 Map<String, Field> fieldMap = getFieldMap(lists.get(k)); row = sheet.createRow(k + 1); j = 0; for (String key : keyList) { /*// 字段Field的属性 String name = fieldMap.get(key).getName(); // 字段Field的属性类型 String type = fieldMap.get(key).getType().getName(); System.out.println("属性名:" + name + ",属性类型:" +type);*/ cell = row.createCell(j); if (fieldMap.get(key).get(lists.get(k)) != null) { cell.setCellValue(fieldMap.get(key).get(lists.get(k)).toString()); cell.setCellStyle(style); } j++; } } flag++; } //设置文件名后缀 SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss"); //定义导出的表名 String fName = URLEncoder.encode(fileName + sdf.format(new Date()).toString() + ".xls", "UTF-8"); ByteArrayOutputStream os = new ByteArrayOutputStream(); wb.write(os); if (os.size() > 0) { response.setContentType("application/octet-stream"); response.addHeader("Content-Disposition", "attachment; filename=" + fName); response.addHeader("Content-Length", "" + os.size()); IOUtils.write(os.toByteArray(), response.getOutputStream()); response.getOutputStream().flush(); } os.close(); } /* * 利用java反射机制获取该类及父类的所有字段信息 */ public static Map<String, Field> getFieldMap(Object obj) { Map<String, Field> map = new HashMap<>(); // 所有字段信息 Field[] fields = obj.getClass().getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); map.put(field.getName(), field); } //获取其父类所有属性(字段信息) Field[] superFields = obj.getClass().getSuperclass().getDeclaredFields(); for (Field field : superFields) { field.setAccessible(true); map.put(field.getName(), field); } return map; } /* * 利用JAVA反射通过实体类名获取其对应属性 * @param 实体类所在bean路径(即实体类在src下的路径),例:entity.Student */ public static Map<String, String> getBeanComment(String bean) { Map<String, String> map = new HashMap<>(); try { Class<?> clz = Class.forName(bean); Field[] strsSub = clz.getDeclaredFields(); Class<?> clzSuper = Class.forName(bean).getSuperclass(); List<Field> strs = new ArrayList<>(); for (Field filed : strsSub) { strs.add(filed); } if (null != clzSuper) { Field[] StrsSuper = clzSuper.getDeclaredFields(); for (Field filed : StrsSuper) { strs.add(filed); } } for (Field field : strs) { Comment comment = field.getAnnotation(Comment.class); if (null == comment) { continue; } String name = field.getName(); if ("id".equals(name)) { continue; } if (StringUtils.isNotBlank(comment.value())) { map.put(name, comment.value()); } } return map; } catch (ClassNotFoundException e) { e.printStackTrace(); return null; } } /*public static void main(String[] args) throws Exception { Student stu = new Student(); stu.setName("LOL"); stu.setAge("10"); stu.setSex("待确定"); stu.setStuClass("黑铁班"); Map<String, String> map = getBeanComment("Student"); Set<String> keySet = map.keySet(); Map<String, Field> fMap = getFieldMap(stu); for (String key : keySet) { String comValue = map.get(key); System.out.println(comValue); // 字段Field的属性 String name = fMap.get(key).getName(); System.out.println("属性名:" + name); // 字段Field的属性类型 String type = fMap.get(key).getType().getName(); System.out.println("属性类型:" +type); String value = fMap.get(key).get(stu).toString(); System.out.println("属性值:" + value); System.out.println("---------------------"); } }*/ }