Springmvc导出Excel(maven)
发布时间:2020-12-15 07:11:02 所属栏目:Java 来源:网络整理
导读:一、导入依赖 dependency groupIdorg.apache.poi/groupId artifactIdpoi/artifactId version 3.9 /version /dependency dependency groupIdorg.apache.poi/groupId artifactIdpoi-ooxml/artifactId version 3.9 /version /dependency ? 二、编写工具类 packa
一、导入依赖 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency> ? 二、编写工具类 package cn.pms.util; import java.io.OutputStream; java.io.UnsupportedEncodingException; java.lang.reflect.Field; java.text.SimpleDateFormat; java.util.Date; java.util.LinkedHashMap; java.util.List; java.util.Map.Entry; javax.servlet.http.HttpServletResponse; org.apache.poi.hssf.usermodel.HSSFCell; org.apache.poi.hssf.usermodel.HSSFCellStyle; org.apache.poi.hssf.usermodel.HSSFRow; org.apache.poi.hssf.usermodel.HSSFSheet; org.apache.poi.hssf.usermodel.HSSFWorkbook; org.slf4j.Logger; org.slf4j.LoggerFactory; /** * 导出Excel * @author Guang * */ public class ExportExcelUtils { private static final Logger logger =LoggerFactory.getLogger(ExportExcelUtils.); * 导出Excel * @param excelName 要导出的excel名称 * list 要导出的数据集合 * fieldMap 中英文字段对应Map,即要导出的excel表头 * response 使用response可以导出到浏览器 * @return */ static <T> void export(String excelName,List<T> list,LinkedHashMap<String,String> fieldMap,HttpServletResponse response){ // 设置默认文件名为当前时间:年月日时分秒 if (excelName==null || excelName=="") { excelName = new SimpleDateFormat("yyyyMMddhhmmss").format( new Date()).toString(); } 设置response头信息 response.reset(); response.setContentType("application/vnd.ms-excel"); 改成输出excel文件 try { response.setHeader("Content-disposition","attachment; filename=" +new String(excelName.getBytes("gb2312"),"ISO-8859-1") + ".xls"); } catch (UnsupportedEncodingException e1) { logger.info(e1.getMessage()); } { 创建一个WorkBook,对应一个Excel文件 HSSFWorkbook wb= HSSFWorkbook(); 在Workbook中,创建一个sheet,对应Excel中的工作薄(sheet) HSSFSheet sheet=wb.createSheet(excelName); 创建单元格,并设置值表头 设置表头居中 HSSFCellStyle style=wb.createCellStyle(); 创建一个居中格式 style.setAlignment(HSSFCellStyle.ALIGN_CENTER); 填充工作表 fillSheet(sheet,list,fieldMap,style); 将文件输出 OutputStream ouputStream = response.getOutputStream(); wb.write(ouputStream); ouputStream.flush(); ouputStream.close(); } (Exception e) { logger.info("导出Excel失败!"); logger.error(e.getMessage()); } } * 根据字段名获取字段对象 * * fieldName * 字段名 * clazz * 包含该字段的类 * @return 字段 static Field getFieldByName(String fieldName,Class<?> clazz) { logger.info("根据字段名获取字段对象:getFieldByName()"); 拿到本类的所有字段 Field[] selfFields = clazz.getDeclaredFields(); 如果本类中存在该字段,则返回 for (Field field : selfFields) { 如果本类中存在该字段,则返回 if (field.getName().equals(fieldName)) { return field; } } 否则,查看父类中是否存在此字段,如果有则返回 Class<?> superClazz = clazz.getSuperclass(); if (superClazz != null && superClazz != Object.) { 递归 getFieldByName(fieldName,superClazz); } 如果本类和父类都没有,则返回空 return null; } * 根据字段名获取字段值 * * fieldName 字段名 * o 对象 * 字段值 * @throws Exception 异常 * static Object getFieldValueByName(String fieldName,Object o) throws Exception { logger.info("根据字段名获取字段值:getFieldValueByName()"); Object value = ; 根据字段名得到字段对象 Field field =如果该字段存在,则取出该字段的值 if (field != ) { field.setAccessible(true);类中的成员变量为private,在类外边使用属性值,故必须进行此操作 value = field.get(o);获取当前对象中当前Field的value } elsethrow new Exception(o.getClass().getSimpleName() + "类不存在字段名 " + fieldName); } value; } * 根据带路径或不带路径的属性名获取属性值,即接受简单属性名, * 如userName等,又接受带路径的属性名,如student.department.name等 * * fieldNameSequence 带路径的属性名或简单属性名 * o 对象 * 属性值 * Exception 异常 * Object getFieldValueByNameSequence(String fieldNameSequence,Object o) Exception { logger.info("根据带路径或不带路径的属性名获取属性值,即接受简单属性名:getFieldValueByNameSequence()"; 将fieldNameSequence进行拆分 String[] attributes = fieldNameSequence.split("."if (attributes.length == 1) { value = getFieldValueByName(fieldNameSequence,o); } 根据数组中第一个连接属性名获取连接属性对象,如student.department.name Object fieldObj = getFieldValueByName(attributes[0],o); 截取除第一个属性名之后的路径 String subFieldNameSequence = fieldNameSequence .substring(fieldNameSequence.indexOf(".") + 1); 递归得到最终的属性对象的值 value = getFieldValueByNameSequence(subFieldNameSequence,fieldObj); } value; } * 向工作表中填充数据 * * sheet * excel的工作表名称 * list * 数据源 * fieldMap * 中英文字段对应关系的Map * style * 表格中的格式 * Exception * 异常 * void fillSheet(HSSFSheet sheet,List<T> list,LinkedHashMap<String,String> fieldMap,HSSFCellStyle style) Exception { logger.info("向工作表中填充数据:fillSheet()" 定义存放英文字段名和中文字段名的数组 String[] enFields = String[fieldMap.size()]; String[] cnFields = String[fieldMap.size()]; 填充数组 int count = 0for (Entry<String,1)"> entry : fieldMap.entrySet()) { enFields[count] = entry.getKey(); cnFields[count] = entry.getValue(); count++; } 在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short HSSFRow row=sheet.createRow((int)0); 填充表头 for (int i = 0; i < cnFields.length; i++) { HSSFCell cell=row.createCell(i); cell.setCellValue(cnFields[i]); cell.setCellStyle(style); sheet.autoSizeColumn(i); } 填充内容 int index = 0; index < list.size(); index++) { row = sheet.createRow(index + 1 获取单个对象 T item = list.get(index); int i = 0; i < enFields.length; i++) { Object objValue = getFieldValueByNameSequence(enFields[i],item); String fieldValue = objValue == null ? "" : objValue.toString(); row.createCell(i).setCellValue(fieldValue); } } } } ? 三、编写Controller cn.pms.controller; java.io.File; java.io.IOException; java.io.InputStream; java.util.HashMap; java.util.Map; javax.servlet.http.HttpServletRequest; org.springframework.beans.factory.annotation.Autowired; org.springframework.http.MediaType; org.springframework.stereotype.Controller; org.springframework.ui.Model; org.springframework.web.bind.annotation.RequestMapping; org.springframework.web.bind.annotation.RequestMethod; org.springframework.web.bind.annotation.RequestParam; org.springframework.web.bind.annotation.ResponseBody; org.springframework.web.multipart.MultipartFile; com.alibaba.fastjson.JSON; com.wordnik.swagger.annotations.Api; com.wordnik.swagger.annotations.ApiOperation; cn.pms.model.User; cn.pms.service.UserService; cn.pms.util.ExcelImportUtil; cn.pms.util.ExportExcelUtils; * 用户Controller * * eluzhu * */ @Controller @RequestMapping("/user") UserController { @Autowired private UserService userService; @RequestMapping(value = "/excel/exportBankCheckInfo",method = RequestMethod.GET) void ExportBankCheckInfo(HttpServletRequest request,HttpServletResponse response) { 得到所要导出的数据 List<User> errLst = userService.selectAllUser(); 定义导出excel的名字 String excelName="用户表" 获取需要转出的excle表头的map字段 LinkedHashMap<String,String> fieldMap =new LinkedHashMap<String,1)">() ; fieldMap.put("userNo","编号"); fieldMap.put("userName","姓名"); fieldMap.put("password","密码"); 导出用户相关信息 ExportExcelUtils().export(excelName,errLst,response); } } ? 四、浏览器输入对应的URL进行测试(成功的标识如下) 控制台打印和浏览器显示 ? ? ? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |