下载数据到Excel,工具类
使用反射将model数据下载到Excel中
- package test.upload.utils;
- import java.lang.reflect.Method;
- import java.math.BigDecimal;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.util.List;
- import java.util.Map;
- import org.apache.poi.hssf.usermodel.HSSFCell;
- import org.apache.poi.hssf.usermodel.HSSFRichTextString;
- import org.apache.poi.hssf.usermodel.HSSFRow;
- import org.apache.poi.hssf.usermodel.HSSFSheet;
- import org.apache.poi.hssf.usermodel.HSSFWorkbook;
- import org.apache.poi.hssf.util.HSSFColor;
- import org.apache.poi.ss.usermodel.CellStyle;
- import org.apache.poi.ss.usermodel.CreationHelper;
- import org.apache.poi.ss.usermodel.Font;
- import org.apache.poi.ss.usermodel.Workbook;
- /**
- * 生成EXCEL的工具类
- *
- * @author duandingyang
- *
- */
- public class ExcelUtils {
- /**
- * 生成EXCEL的通用方法
- *
- * @param filePath 生成EXCEL的地址
- * @param clazz 绑定数据的类型
- * @param list 数据列表
- * @param map EXCEL表头信息
- * @throws Exception
- */
- public static HSSFWorkbook generateExcel(Class<?> clazz, List<?> list,
- Map<String, ExcelTitle> map) throws Exception {
- HSSFWorkbook wb = new HSSFWorkbook();
- CreationHelper helper = wb.getCreationHelper();
- HSSFSheet sheet = wb.createSheet("sheet1");
- HSSFRow row = sheet.createRow(0);
- CellStyle cellStyle = ExcelUtils.createStyleCell(wb);
- cellStyle.setFont(ExcelUtils.createFonts(wb));
- int i = 0;
- for (String attr : map.keySet()) {
- sheet.setColumnWidth(i, 5000);
- ExcelTitle excelTitle = map.get(attr);
- int order = excelTitle.getOrder();
- String title = excelTitle.getTitle();
- HSSFCell cell = row.createCell(order);
- cellStyle = ExcelUtils.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER,
- CellStyle.VERTICAL_CENTER);
- cellStyle.setWrapText(true);
- cell.setCellStyle(cellStyle);
- cell.setCellValue(title);
- i++;
- }
- int rowNum = 1;
- if (list != null) {
- for (Object obj : list) {
- row = sheet.createRow(rowNum);
- for (String attr : map.keySet()) {
- ExcelTitle excelTitle = map.get(attr);
- int order = excelTitle.getOrder();
- Class<?> type = excelTitle.getType();
- String getMethod = "get" + attr.substring(0, 1).toUpperCase()
- + attr.substring(1);
- Method method = clazz.getMethod(getMethod, new Class[] {});
- Object value = method.invoke(obj, new Object[] {});
- HSSFCell cell = row.createCell(order);
- if (value != null) {
- if (Double.class.equals(type)) {
- cellStyle = ExcelUtils.setCellStyleAlignment(cellStyle,
- CellStyle.ALIGN_RIGHT, CellStyle.VERTICAL_CENTER);
- cellStyle = ExcelUtils.setCellFormat(helper, cellStyle, "#,##0.00");
- cell.setCellStyle(cellStyle);
- double doubleValue = Double.valueOf(value.toString());
- cell.setCellValue(doubleValue);
- } else if (Long.class.equals(type)) {
- cellStyle = ExcelUtils.setCellStyleAlignment(cellStyle,
- CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);
- cell.setCellStyle(cellStyle);
- long longValue = Long.valueOf(value.toString());
- cell.setCellValue(longValue);
- } else if (String.class.equals(type)) {
- // cellStyle = ExcelUtils.setCellStyleAlignment(cellStyle,
- // CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);
- // cell.setCellStyle(cellStyle);
- cellStyle.setWrapText(true);
- cell.setCellStyle(cellStyle);
- cell.setCellValue(new HSSFRichTextString(value.toString()));
- } else if (Date.class.equals(type)) {
- // TODO 处理时间
- SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- String ctime = format.format(value);
- cell.setCellValue(ctime);
- }
- else if (BigDecimal.class.equals(type)) {
- BigDecimal bigDecimal=(BigDecimal) value;
- String bigDecimalValue = bigDecimal.toString();
- cell.setCellValue(bigDecimalValue);
- }else if(Integer.class.equals(type)){
- if(value != null){
- cell.setCellValue(Integer.parseInt((value.toString())));
- }
- }
- }
- }
- rowNum++;
- }
- }
- return wb;
- }
- public static CellStyle createStyleCell(Workbook wb) {
- CellStyle cellStyle = wb.createCellStyle();
- // // 设置一个单元格边框颜色
- // cellStyle.setBorderBottom(CellStyle.BORDER_THIN);
- // cellStyle.setBorderTop(CellStyle.BORDER_THIN);
- // cellStyle.setBorderLeft(CellStyle.BORDER_THIN);
- // cellStyle.setBorderRight(CellStyle.BORDER_THIN);
- // // 设置一个单元格边框颜色
- // cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
- // cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
- // cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
- // cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
- return cellStyle;
- }
- /**
- * 设置文字在单元格里面的位置 CellStyle.ALIGN_CENTER CellStyle.VERTICAL_CENTER
- *
- * @param cellStyle
- * @param halign
- * @param valign
- * @return
- */
- public static CellStyle setCellStyleAlignment(CellStyle cellStyle, short halign, short valign) {
- // 设置上下
- cellStyle.setAlignment(halign);
- // 设置左右
- cellStyle.setVerticalAlignment(valign);
- return cellStyle;
- }
- /**
- * 格式化单元格 如#,##0.00,m/d/yy去HSSFDataFormat或XSSFDataFormat里面找
- *
- * @param cellStyle
- * @param fmt
- * @return
- */
- public static CellStyle setCellFormat(CreationHelper helper, CellStyle cellStyle, String fmt) {
- // 还可以用其它方法创建format
- cellStyle.setDataFormat(helper.createDataFormat().getFormat(fmt));
- return cellStyle;
- }
- /**
- * 设置字体
- *
- * @param wb
- * @return
- */
- public static Font createFonts(Workbook wb) {
- // 创建Font对象
- Font font = wb.createFont();
- // 设置字体
- font.setFontName("微软雅黑");
- // 着色
- font.setColor(HSSFColor.BLACK.index);
- return font;
- }
- /**
- * 生成EXCEL通用方法使用的表头类
- *
- * @author cuijianxing
- *
- */
- public static class ExcelTitle {
- private int order;
- private Class<?> type;
- private String title;
- public int getOrder() {
- return order;
- }
- public void setOrder(int order) {
- this.order = order;
- }
- public String getTitle() {
- return title;
- }
- public void setTitle(String title) {
- this.title = title;
- }
- public Class<?> getType() {
- return type;
- }
- public void setType(Class<?> type) {
- this.type = type;
- }
- public ExcelTitle(int order, Class<?> type, String title) {
- super();
- this.order = order;
- this.type = type;
- this.title = title;
- }
- }
}
controller层:
- @RequestMapping(value = "/downloadUserData", method = RequestMethod.GET)
- public void downloadUserData(HttpServletRequest request,
- HttpServletResponse response) {
- response.setContentType("application/x-excel");
- response.setHeader("content-disposition", "attachment;filename="
- + "UserData.xls");
- response.setCharacterEncoding("UTF-8");
- List<User> users = userService.getUserList();
- Map<String, ExcelUtils.ExcelTitle> titleMap = this.getExcelTitleMap();
- OutputStream ouputStream = null;
- try {
- HSSFWorkbook workBook = ExcelUtils.generateExcel(User.class, users,
- titleMap);
- ouputStream = response.getOutputStream();
- workBook.write(ouputStream);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- ouputStream.flush();
- ouputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- private Map<String, ExcelUtils.ExcelTitle> getExcelTitleMap() {
- Map<String, ExcelUtils.ExcelTitle> titleMap = new HashMap<String, ExcelUtils.ExcelTitle>();
- ExcelUtils.ExcelTitle excelTitle0 = new ExcelUtils.ExcelTitle(0,
- String.class, "序号");
- titleMap.put("id", excelTitle0);
- ExcelUtils.ExcelTitle excelTitle1 = new ExcelUtils.ExcelTitle(1,
- String.class, "姓名");
- titleMap.put("name", excelTitle1);
- ExcelUtils.ExcelTitle excelTitle2 = new ExcelUtils.ExcelTitle(2,
- String.class, "电话");
- titleMap.put("phone", excelTitle2);
- ExcelUtils.ExcelTitle excelTitle3 = new ExcelUtils.ExcelTitle(2,
- String.class, "地址");
- titleMap.put("address", excelTitle3);
- return titleMap;
}
代码下载:
https://github.com/vincentduan/UploadExcel.git
下载数据到Excel,工具类的更多相关文章
- Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类
Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类 ============================== ©Copyright 蕃薯耀 20 ...
- Python Excel工具类封装, 给excel表头搞点颜色
封装Excel工具类 我们常用的excel工具类,读有xlrd,写有xlwt.有读有写,新一代库有pandas,openpyxl等等. 大家用法都差不多,今天博主就介绍新手最爱,我也爱的xlrd和xl ...
- excel工具类
excel工具类 import com.iport.framework.util.ValidateUtil; import org.apache.commons.lang3.StringUtils; ...
- 导入导出Excel工具类ExcelUtil
前言 前段时间做的分布式集成平台项目中,许多模块都用到了导入导出Excel的功能,于是决定封装一个ExcelUtil类,专门用来处理Excel的导入和导出 本项目的持久化层用的是JPA(底层用hibe ...
- 自己封装的poi操作Excel工具类
自己封装的poi操作Excel工具类 在上一篇文章<使用poi读写Excel>中分享了一下poi操作Excel的简单示例,这次要分享一下我封装的一个Excel操作的工具类. 该工具类主要完 ...
- java 解析excel工具类
java 解析excel工具类 CreateTime--2018年3月5日16:48:08 Author:Marydon ReadExcelUtils.java import java.io.Fi ...
- Java解析Excel工具类(兼容xls和xlsx)
依赖jar <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml&l ...
- java里poi操作Excel工具类【我改】
参考原文: https://www.cnblogs.com/yizhang/p/7244917.html 我改: package test; import java.io.File; import j ...
- java操作excel 工具类
java操作excel 可参考https://blog.csdn.net/xunwei0303/article/details/53213130 直接上代码: 一.java生成excel文件: pac ...
- javaEE开发之导出excel工具类
web开发中,一个系统的普通需求也包含导出excel,一般採用POI做统计报表导出excel. 导出excel工具类: import java.io.FileOutputStream; import ...
随机推荐
- Python3简明教程(十二)—— 模块
在这节我们将要学习 Python 模块相关知识.包括模块的概念和导入方法,包的概念和使用,第三方模块的介绍,命令行参数的使用等. 模块 到目前为止,我们在 Python 解释器中写的所有代码都在我们退 ...
- Kubernetes 架构(下)【转】
上一节我们讨论了 Kubernetes 架构 Master 上运行的服务,本节讨论 Node 节点. Node 是 Pod 运行的地方,Kubernetes 支持 Docker.rkt 等容器 Run ...
- 最短路 || Codeforces 938D Buy a Ticket
题意:从城市u到v(双向)要花w钱,每个城市看演唱会要花不同的门票钱,求每个城市的人要看一场演唱会花费最少多少(可以在这个城市看,也可以坐车到别的城市看,然后再坐车回来) 思路:本来以为是多源..实际 ...
- mysql的sql语句练习的2个网址
sql语句练习: https://blog.csdn.net/mrbcy/article/details/68965271 完成. https://blog.csdn.net/flycat296/ar ...
- vueshengmingzhouqi
首先,每个Vue实例在被创建之前都要经过一系列的初始化过程,这个过程就是vue的生命周期.首先看一张图吧~这是官方文档上的图片相信大家一定都会很熟悉: 可以看到在vue一整个的生命周期中会有很多钩子函 ...
- 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 ...
- (2) LVS负载均衡:VS_TUN和VS_DR的arp问题
1. ARP协议简介 ARP(Address Resolution Protocol)协议称为地址解析协议,用于将主机IP地址解析为主机的MAC地址,即IP-->MAC之间一一映射. RARP协 ...
- HTML5新增的主体元素article、section、nav、aside、time元素和pubdate属性
article artticle元素代表文档.页面或应用程序中独立的.完整的.可以独自被外部引用的内容.它可以是一篇博客或者报刊中的文章,一篇论坛帖子,一段用户评论或者独立的插件或其他任何独立的内容. ...
- Linux 基本操作指南
Linux基本操作 1. su 切换用户 2.exit 退出当前登录用户 3.useradd 用户名 -m 在home目录下 创建一个和用户名同名的目录,并添加一个用户 (有root权限才能 ...
- 【URAL 1989】 Subpalindromes(线段树维护哈希)
Description You have a string and queries of two types: replace i'th character of the string by char ...