使用反射将model数据下载到Excel中

  1. package test.upload.utils;
  2.  
  3. import java.lang.reflect.Method;
  4. import java.math.BigDecimal;
  5. import java.text.SimpleDateFormat;
  6. import java.util.Date;
  7. import java.util.List;
  8. import java.util.Map;
  9.  
  10. import org.apache.poi.hssf.usermodel.HSSFCell;
  11. import org.apache.poi.hssf.usermodel.HSSFRichTextString;
  12. import org.apache.poi.hssf.usermodel.HSSFRow;
  13. import org.apache.poi.hssf.usermodel.HSSFSheet;
  14. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  15. import org.apache.poi.hssf.util.HSSFColor;
  16. import org.apache.poi.ss.usermodel.CellStyle;
  17. import org.apache.poi.ss.usermodel.CreationHelper;
  18. import org.apache.poi.ss.usermodel.Font;
  19. import org.apache.poi.ss.usermodel.Workbook;
  20.  
  21. /**
  22.  * 生成EXCEL的工具类
  23.  * 
  24.  * @author duandingyang
  25.  * 
  26.  */
  27. public class ExcelUtils {
  28.  
  29.     /**
  30.      * 生成EXCEL的通用方法
  31.      * 
  32.      * @param filePath 生成EXCEL的地址
  33.      * @param clazz 绑定数据的类型
  34.      * @param list 数据列表
  35.      * @param map EXCEL表头信息
  36.      * @throws Exception
  37.      */
  38.     public static HSSFWorkbook generateExcel(Class<?> clazz, List<?> list,
  39.             Map<String, ExcelTitle> map) throws Exception {
  40.  
  41.         HSSFWorkbook wb = new HSSFWorkbook();
  42.         CreationHelper helper = wb.getCreationHelper();
  43.         HSSFSheet sheet = wb.createSheet("sheet1");
  44.         HSSFRow row = sheet.createRow(0);
  45.         CellStyle cellStyle = ExcelUtils.createStyleCell(wb);
  46.         cellStyle.setFont(ExcelUtils.createFonts(wb));
  47.         int i = 0;
  48.         for (String attr : map.keySet()) {
  49.             sheet.setColumnWidth(i, 5000);
  50.             ExcelTitle excelTitle = map.get(attr);
  51.             int order = excelTitle.getOrder();
  52.             String title = excelTitle.getTitle();
  53.             HSSFCell cell = row.createCell(order);
  54.             cellStyle = ExcelUtils.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER,
  55.                     CellStyle.VERTICAL_CENTER);
  56.             cellStyle.setWrapText(true);    
  57.             cell.setCellStyle(cellStyle);
  58.             cell.setCellValue(title);
  59.             i++;
  60.         }
  61.         int rowNum = 1;
  62.         if (list != null) {
  63.             for (Object obj : list) {
  64.                 row = sheet.createRow(rowNum);
  65.                 for (String attr : map.keySet()) {
  66.                     ExcelTitle excelTitle = map.get(attr);
  67.                     int order = excelTitle.getOrder();
  68.                     Class<?> type = excelTitle.getType();
  69.                     String getMethod = "get" + attr.substring(0, 1).toUpperCase()
  70.                             + attr.substring(1);
  71.                     Method method = clazz.getMethod(getMethod, new Class[] {});
  72.                     Object value = method.invoke(obj, new Object[] {});
  73.                     HSSFCell cell = row.createCell(order);
  74.                     if (value != null) {
  75.                         if (Double.class.equals(type)) {
  76.                             cellStyle = ExcelUtils.setCellStyleAlignment(cellStyle,
  77.                                     CellStyle.ALIGN_RIGHT, CellStyle.VERTICAL_CENTER);
  78.                             cellStyle = ExcelUtils.setCellFormat(helper, cellStyle, "#,##0.00");
  79.                             cell.setCellStyle(cellStyle);
  80.                             double doubleValue = Double.valueOf(value.toString());
  81.                             cell.setCellValue(doubleValue);
  82.                         } else if (Long.class.equals(type)) {
  83.                             cellStyle = ExcelUtils.setCellStyleAlignment(cellStyle,
  84.                                     CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);
  85.                             cell.setCellStyle(cellStyle);
  86.                             long longValue = Long.valueOf(value.toString());
  87.                             cell.setCellValue(longValue);
  88.                         } else if (String.class.equals(type)) {
  89.                             //                            cellStyle = ExcelUtils.setCellStyleAlignment(cellStyle,
  90.                             //                                    CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);
  91.                             //                            cell.setCellStyle(cellStyle);
  92.                             cellStyle.setWrapText(true);   
  93.                             cell.setCellStyle(cellStyle);
  94.                             cell.setCellValue(new HSSFRichTextString(value.toString()));
  95.                         } else if (Date.class.equals(type)) {
  96.                             // TODO 处理时间
  97.                             SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  98.                             String ctime = format.format(value); 
  99.                             cell.setCellValue(ctime);
  100.                         }
  101.                         else if (BigDecimal.class.equals(type)) {
  102.                             BigDecimal bigDecimal=(BigDecimal) value;
  103.                             String bigDecimalValue = bigDecimal.toString();
  104.                             cell.setCellValue(bigDecimalValue);
  105.                         }else if(Integer.class.equals(type)){
  106.                             if(value != null){
  107.                                  cell.setCellValue(Integer.parseInt((value.toString())));
  108.                             }
  109.                         }
  110.                     }
  111.                 }
  112.                 rowNum++;
  113.             }
  114.         }
  115.         return wb;
  116.     }
  117.  
  118.     public static CellStyle createStyleCell(Workbook wb) {
  119.         CellStyle cellStyle = wb.createCellStyle();
  120.         //        // 设置一个单元格边框颜色
  121.         //        cellStyle.setBorderBottom(CellStyle.BORDER_THIN);
  122.         //        cellStyle.setBorderTop(CellStyle.BORDER_THIN);
  123.         //        cellStyle.setBorderLeft(CellStyle.BORDER_THIN);
  124.         //        cellStyle.setBorderRight(CellStyle.BORDER_THIN);
  125.         //        // 设置一个单元格边框颜色
  126.         //        cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
  127.         //        cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
  128.         //        cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
  129.         //        cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
  130.  
  131.         return cellStyle;
  132.     }
  133.  
  134.     /**
  135.      * 设置文字在单元格里面的位置 CellStyle.ALIGN_CENTER CellStyle.VERTICAL_CENTER
  136.      * 
  137.      * @param cellStyle
  138.      * @param halign
  139.      * @param valign
  140.      * @return
  141.      */
  142.     public static CellStyle setCellStyleAlignment(CellStyle cellStyle, short halign, short valign) {
  143.         // 设置上下
  144.         cellStyle.setAlignment(halign);
  145.         // 设置左右
  146.         cellStyle.setVerticalAlignment(valign);
  147.         return cellStyle;
  148.     }
  149.  
  150.     /**
  151.      * 格式化单元格 如#,##0.00,m/d/yy去HSSFDataFormat或XSSFDataFormat里面找
  152.      * 
  153.      * @param cellStyle
  154.      * @param fmt
  155.      * @return
  156.      */
  157.     public static CellStyle setCellFormat(CreationHelper helper, CellStyle cellStyle, String fmt) {
  158.         // 还可以用其它方法创建format
  159.         cellStyle.setDataFormat(helper.createDataFormat().getFormat(fmt));
  160.         return cellStyle;
  161.     }
  162.  
  163.     /**
  164.      * 设置字体
  165.      * 
  166.      * @param wb
  167.      * @return
  168.      */
  169.     public static Font createFonts(Workbook wb) {
  170.         // 创建Font对象
  171.         Font font = wb.createFont();
  172.         // 设置字体
  173.         font.setFontName("微软雅黑");
  174.         // 着色
  175.         font.setColor(HSSFColor.BLACK.index);
  176.         return font;
  177.     }
  178.  
  179.     /**
  180.      * 生成EXCEL通用方法使用的表头类
  181.      * 
  182.      * @author cuijianxing
  183.      * 
  184.      */
  185.     public static class ExcelTitle {
  186.  
  187.         private int order;
  188.  
  189.         private Class<?> type;
  190.  
  191.         private String title;
  192.  
  193.         public int getOrder() {
  194.             return order;
  195.         }
  196.  
  197.         public void setOrder(int order) {
  198.             this.order = order;
  199.         }
  200.  
  201.         public String getTitle() {
  202.             return title;
  203.         }
  204.  
  205.         public void setTitle(String title) {
  206.             this.title = title;
  207.         }
  208.  
  209.         public Class<?> getType() {
  210.             return type;
  211.         }
  212.  
  213.         public void setType(Class<?> type) {
  214.             this.type = type;
  215.         }
  216.  
  217.         public ExcelTitle(int order, Class<?> type, String title) {
  218.             super();
  219.             this.order = order;
  220.             this.type = type;
  221.             this.title = title;
  222.         }
  223.  
  224.     }

}

controller层:

  1. @RequestMapping(value = "/downloadUserData", method = RequestMethod.GET)
  2.     public void downloadUserData(HttpServletRequest request,
  3.             HttpServletResponse response) {
  4.         response.setContentType("application/x-excel");
  5.         response.setHeader("content-disposition", "attachment;filename="
  6.                 + "UserData.xls");
  7.         response.setCharacterEncoding("UTF-8");
  8.         List<User> users = userService.getUserList();
  9.         Map<String, ExcelUtils.ExcelTitle> titleMap = this.getExcelTitleMap();
  10.         OutputStream ouputStream = null;
  11.         try {
  12.             HSSFWorkbook workBook = ExcelUtils.generateExcel(User.class, users,
  13.                     titleMap);
  14.             ouputStream = response.getOutputStream();
  15.             workBook.write(ouputStream);
  16.         } catch (Exception e) {
  17.             e.printStackTrace();
  18.         } finally {
  19.             try {
  20.                 ouputStream.flush();
  21.                 ouputStream.close();
  22.             } catch (IOException e) {
  23.                 e.printStackTrace();
  24.             }
  25.         }
  26.     }
  27.  
  28.     private Map<String, ExcelUtils.ExcelTitle> getExcelTitleMap() {
  29.         Map<String, ExcelUtils.ExcelTitle> titleMap = new HashMap<String, ExcelUtils.ExcelTitle>();
  30.  
  31.         ExcelUtils.ExcelTitle excelTitle0 = new ExcelUtils.ExcelTitle(0,
  32.                 String.class, "序号");
  33.         titleMap.put("id", excelTitle0);
  34.  
  35.         ExcelUtils.ExcelTitle excelTitle1 = new ExcelUtils.ExcelTitle(1,
  36.                 String.class, "姓名");
  37.         titleMap.put("name", excelTitle1);
  38.  
  39.         ExcelUtils.ExcelTitle excelTitle2 = new ExcelUtils.ExcelTitle(2,
  40.                 String.class, "电话");
  41.         titleMap.put("phone", excelTitle2);
  42.  
  43.         ExcelUtils.ExcelTitle excelTitle3 = new ExcelUtils.ExcelTitle(2,
  44.                 String.class, "地址");
  45.         titleMap.put("address", excelTitle3);
  46.  
  47.         return titleMap;

}

代码下载:

https://github.com/vincentduan/UploadExcel.git

下载数据到Excel,工具类的更多相关文章

  1. Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类

    Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类 ============================== ©Copyright 蕃薯耀 20 ...

  2. Python Excel工具类封装, 给excel表头搞点颜色

    封装Excel工具类 我们常用的excel工具类,读有xlrd,写有xlwt.有读有写,新一代库有pandas,openpyxl等等. 大家用法都差不多,今天博主就介绍新手最爱,我也爱的xlrd和xl ...

  3. excel工具类

    excel工具类 import com.iport.framework.util.ValidateUtil; import org.apache.commons.lang3.StringUtils; ...

  4. 导入导出Excel工具类ExcelUtil

    前言 前段时间做的分布式集成平台项目中,许多模块都用到了导入导出Excel的功能,于是决定封装一个ExcelUtil类,专门用来处理Excel的导入和导出 本项目的持久化层用的是JPA(底层用hibe ...

  5. 自己封装的poi操作Excel工具类

    自己封装的poi操作Excel工具类 在上一篇文章<使用poi读写Excel>中分享了一下poi操作Excel的简单示例,这次要分享一下我封装的一个Excel操作的工具类. 该工具类主要完 ...

  6. java 解析excel工具类

      java 解析excel工具类 CreateTime--2018年3月5日16:48:08 Author:Marydon ReadExcelUtils.java import java.io.Fi ...

  7. Java解析Excel工具类(兼容xls和xlsx)

    依赖jar <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml&l ...

  8. java里poi操作Excel工具类【我改】

    参考原文: https://www.cnblogs.com/yizhang/p/7244917.html 我改: package test; import java.io.File; import j ...

  9. java操作excel 工具类

    java操作excel 可参考https://blog.csdn.net/xunwei0303/article/details/53213130 直接上代码: 一.java生成excel文件: pac ...

  10. javaEE开发之导出excel工具类

    web开发中,一个系统的普通需求也包含导出excel,一般採用POI做统计报表导出excel. 导出excel工具类: import java.io.FileOutputStream; import ...

随机推荐

  1. Python3简明教程(十二)—— 模块

    在这节我们将要学习 Python 模块相关知识.包括模块的概念和导入方法,包的概念和使用,第三方模块的介绍,命令行参数的使用等. 模块 到目前为止,我们在 Python 解释器中写的所有代码都在我们退 ...

  2. Kubernetes 架构(下)【转】

    上一节我们讨论了 Kubernetes 架构 Master 上运行的服务,本节讨论 Node 节点. Node 是 Pod 运行的地方,Kubernetes 支持 Docker.rkt 等容器 Run ...

  3. 最短路 || Codeforces 938D Buy a Ticket

    题意:从城市u到v(双向)要花w钱,每个城市看演唱会要花不同的门票钱,求每个城市的人要看一场演唱会花费最少多少(可以在这个城市看,也可以坐车到别的城市看,然后再坐车回来) 思路:本来以为是多源..实际 ...

  4. mysql的sql语句练习的2个网址

    sql语句练习: https://blog.csdn.net/mrbcy/article/details/68965271 完成. https://blog.csdn.net/flycat296/ar ...

  5. vueshengmingzhouqi

    首先,每个Vue实例在被创建之前都要经过一系列的初始化过程,这个过程就是vue的生命周期.首先看一张图吧~这是官方文档上的图片相信大家一定都会很熟悉: 可以看到在vue一整个的生命周期中会有很多钩子函 ...

  6. Oracle 11G RAC 修改IP

    实验环境 类别 修改前 修改后 PUBLIC 172.18.4.182 rac1 192.168.56.10 rac1 172.18.4.184 rac2 192.168.56.20 rac2 PRI ...

  7. (2) LVS负载均衡:VS_TUN和VS_DR的arp问题

    1. ARP协议简介 ARP(Address Resolution Protocol)协议称为地址解析协议,用于将主机IP地址解析为主机的MAC地址,即IP-->MAC之间一一映射. RARP协 ...

  8. HTML5新增的主体元素article、section、nav、aside、time元素和pubdate属性

    article artticle元素代表文档.页面或应用程序中独立的.完整的.可以独自被外部引用的内容.它可以是一篇博客或者报刊中的文章,一篇论坛帖子,一段用户评论或者独立的插件或其他任何独立的内容. ...

  9. Linux 基本操作指南

    Linux基本操作 1. su  切换用户   2.exit 退出当前登录用户 3.useradd 用户名  -m  在home目录下 创建一个和用户名同名的目录,并添加一个用户 (有root权限才能 ...

  10. 【URAL 1989】 Subpalindromes(线段树维护哈希)

    Description You have a string and queries of two types: replace i'th character of the string by char ...