Java Annotation 应用 -- 导出Excel表格
相关知识链接:
Introspector(内省)
POI
1.声明注解
package com.ciic.component.excel;import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;/****/ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface ExcelAnnotation {// excel导出时标题显示的名字,如果没有设置Annotation属性,将不会被导出和导入public String exportName(); }
2.应用注解
package com.ciic.history.entity;import com.ciic.component.excel.ExcelAnnotation; import com.ciic.history.common.ExportBase;//客户一揽子表 public class EsinnerLimeCustomerPreviewIndex extends ExportBase {@ExcelAnnotation(exportName = "客户名称")private String imscustomername;@ExcelAnnotation(exportName = "客户编号")private String imscustomercode;@ExcelAnnotation(exportName = "合同方式")private long imscontracttypea;@ExcelAnnotation(exportName = "月服务费")private String serviceimstotalfee;@ExcelAnnotation(exportName = "雇员人数")private long employeecount;@ExcelAnnotation(exportName = "应收金额")private String imstotalfee;@ExcelAnnotation(exportName = "实收金额")private String doneimstotalfee;@ExcelAnnotation(exportName = "应付金额")private String imssocialinsurancetfee;@ExcelAnnotation(exportName = "实付金额")private String dtlimssocialinsurancetfee;@ExcelAnnotation(exportName = "最后修改日期")private String modifieddate;@ExcelAnnotation(exportName = "客户简称")private String imscustomershort;@ExcelAnnotation(exportName = "合作方式")private long imscontracttypeb;@ExcelAnnotation(exportName = "客户经理")private String imscustomerclerk;@ExcelAnnotation(exportName = "未付款日期")private String unimspaynoticemonth;@ExcelAnnotation(exportName = "已交付日期")private String doneimspaynoticemonth;getter()setter() }
3.解析注解
3.1 获取数据
public void exportCustomerPreview(EsinnerLimeCustomerPreviewIndex customerPreview, HttpServletResponse response)throws Exception{JsonEntity entity =XAServiceL.customerPreviewSearch(customerPreview,customerPreview.getPage(),customerPreview.getRows());ExcelExport excelExport= new ExcelExport();response.reset();String fileName="";if(StringUtils.isBlank(customerPreview.getExcelName())){fileName="客户一揽子表/第"+customerPreview.getPage()+"页.xls";}else{fileName=customerPreview.getExcelName()+"/第"+customerPreview.getPage()+"页.xls";}response.setContentType("application/form-data;charset=UTF-8");response.addHeader("Content-Disposition", "attachment;filename=\""+ new String(fileName.getBytes("UTF-8"),"UTF-8") + "\"");System.out.println(Arrays.toString(entity.getRows().toArray()));List<EsinnerLimeCustomerPreviewIndex> outExcel=new ArrayList<EsinnerLimeCustomerPreviewIndex>();for(int i=0;i<entity.getRows().size();i++){outExcel.add(MapBeanConvert.toBean(EsinnerLimeCustomerPreviewIndex.class,(Map) entity.getRows().get(i)));}excelExport.exportExcel(customerPreview.getExcelName(),outExcel,response.getOutputStream());}
3.2 解析注解
/*** 将一个 Map 对象转化为一个 JavaBean** @param clazz 要转化的类型* @param map 包含属性值的 map* @return 转化出来的 JavaBean 对象* @throws IntrospectionException 如果分析类属性失败* @throws IllegalAccessException 如果实例化 JavaBean 失败* @throws InstantiationException 如果实例化 JavaBean 失败* @throws InvocationTargetException 如果调用属性的 setter 方法失败*/@SuppressWarnings("rawtypes")public static <T> T toBean(Class<T> clazz, Map map) {T obj = null;String name = "";try {BeanInfo beanInfo = Introspector.getBeanInfo(clazz);obj = clazz.newInstance(); // 创建 JavaBean 对象// 给 JavaBean 对象的属性赋值PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();for (int i = 0; i < propertyDescriptors.length; i++) {PropertyDescriptor descriptor = propertyDescriptors[i];String propertyName = descriptor.getName();name = propertyName;if (map.containsKey(propertyName)) {// 下面一句可以 try 起来,这样当一个属性赋值失败的时候就不会影响其他属性赋值。Object value = map.get(propertyName);if ("".equals(value)) {value = null;}Object[] args = new Object[1];args[0] = value;try {descriptor.getWriteMethod().invoke(obj, args);} catch (InvocationTargetException e) {System.out.println("字段映射失败");}}}} catch (IllegalAccessException e) {System.out.println("实例化 JavaBean 失败");} catch (IntrospectionException e) {System.out.println("分析类属性失败");} catch (IllegalArgumentException e) { // e.printStackTrace(); System.err.println(name);System.out.println("映射错误");} catch (InstantiationException e) {System.out.println("实例化 JavaBean 失败");}return (T) obj;}
3.3 导出Excel
package com.ciic.component.excel;import org.apache.poi.hssf.usermodel.*;import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.*;/****/ public class ExcelExport<T> {/*** @param title 标题* @param dataset 集合* @param out 输出流*/public void exportExcel(String title, Collection<T> dataset,OutputStream out) {// 声明一个工作薄try {//首先检查数据看是否是正确的Iterator<T> its = dataset.iterator();if (dataset == null || !its.hasNext() || title == null || out == null) {throw new Exception("传入的数据不对!");}T ts = (T) its.next();HSSFWorkbook workbook = new HSSFWorkbook();// 生成一个表格HSSFSheet sheet = workbook.createSheet(title);// 设置表格默认列宽度为15个字节sheet.setDefaultColumnWidth(15);// 生成一个样式HSSFCellStyle style = workbook.createCellStyle();// 设置标题样式 // style = ExcelStyle.setHeadStyle(workbook, style); // // 生成并设置主体样式 // HSSFCellStyle style2 = workbook.createCellStyle(); // style2 = ExcelStyle.setbodyStyle(workbook, style2);// 得到所有字段 Field filed[] = ts.getClass().getDeclaredFields();// 标题List<String> exportfieldtile = new ArrayList<String>();// 导出的字段List<String> fiedName = new ArrayList<String>();// 遍历整个filedfor (int i = 0; i < filed.length; i++) {Field f = filed[i];ExcelAnnotation exa = f.getAnnotation(ExcelAnnotation.class);// 如果设置了annottionif (exa != null) {String exprot = exa.exportName();// 添加到标题 exportfieldtile.add(exprot);// 添加到需要导出的字段 fiedName.add(f.getName());}}// 产生表格标题行HSSFRow row = sheet.createRow(0);for (int i = 0; i < exportfieldtile.size(); i++) {HSSFCell cell = row.createCell(i);cell.setCellStyle(style);HSSFRichTextString text = new HSSFRichTextString(exportfieldtile.get(i));cell.setCellValue(text);}Iterator<T> it = dataset.iterator();int index = 0;// 循环整个集合while (it.hasNext()) {index++;row = sheet.createRow(index);T t = (T) it.next();for (int k = 0; k < fiedName.size(); k++) {HSSFCell cell = row.createCell(k);String fieldname = fiedName.get(k);String getMethodName = "get"+ fieldname.substring(0, 1).toUpperCase()+ fieldname.substring(1);Class tCls = t.getClass();Method getMethod = tCls.getMethod(getMethodName,new Class[]{});Object value = getMethod.invoke(t, new Object[]{});String textValue = getValue(value);HSSFRichTextString richString = new HSSFRichTextString(textValue);cell.setCellValue(richString);}}workbook.write(out);} catch (Exception e) {e.printStackTrace();}}/*** @param title 标题* @param dataset 集合*/public File exportExcel(String title, Collection<T> dataset) {OutputStream out = null;File file = null;// 声明一个工作薄try {//首先检查数据看是否是正确的Iterator<T> its = dataset.iterator();if (dataset == null || !its.hasNext() || title == null) {throw new Exception("传入的数据不对!");}T ts = (T) its.next();HSSFWorkbook workbook = new HSSFWorkbook();// 生成一个表格HSSFSheet sheet = workbook.createSheet(title);// 设置表格默认列宽度为15个字节sheet.setDefaultColumnWidth(15);// 生成一个样式HSSFCellStyle style = workbook.createCellStyle();// 设置标题样式 // style = ExcelStyle.setHeadStyle(workbook, style); // // 生成并设置主体样式 // HSSFCellStyle style2 = workbook.createCellStyle(); // style2 = ExcelStyle.setbodyStyle(workbook, style2);// 得到所有字段 Field filed[] = ts.getClass().getDeclaredFields();// 标题List<String> exportfieldtile = new ArrayList<String>();// 导出的字段List<String> fiedName = new ArrayList<String>();// 遍历整个filedfor (int i = 0; i < filed.length; i++) {Field f = filed[i];ExcelAnnotation exa = f.getAnnotation(ExcelAnnotation.class);// 如果设置了annottionif (exa != null) {String exprot = exa.exportName();// 添加到标题 exportfieldtile.add(exprot);// 添加到需要导出的字段 fiedName.add(f.getName());}}// 产生表格标题行HSSFRow row = sheet.createRow(0);for (int i = 0; i < exportfieldtile.size(); i++) {HSSFCell cell = row.createCell(i);cell.setCellStyle(style);HSSFRichTextString text = new HSSFRichTextString(exportfieldtile.get(i));cell.setCellValue(text);}Iterator<T> it = dataset.iterator();int index = 0;// 循环整个集合while (it.hasNext()) {index++;row = sheet.createRow(index);T t = (T) it.next();for (int k = 0; k < fiedName.size(); k++) {HSSFCell cell = row.createCell(k);String fieldname = fiedName.get(k);String getMethodName = "get"+ fieldname.substring(0, 1).toUpperCase()+ fieldname.substring(1);Class tCls = t.getClass();Method getMethod = tCls.getMethod(getMethodName,new Class[]{});Object value = getMethod.invoke(t, new Object[]{});String textValue = getValue(value);HSSFRichTextString richString = new HSSFRichTextString(textValue);cell.setCellValue(richString);}}file = new File("/tmp/testOne.xls");out = new FileOutputStream(file);workbook.write(out);} catch (Exception e) {e.printStackTrace();} finally {try {if (out != null) {out.close();}} catch (IOException e) {e.printStackTrace();}}return file;}private String getValue(Object value) {String textValue = "";if (value == null)return textValue;if (value instanceof Boolean) {boolean bValue = (Boolean) value;textValue = "是";if (!bValue) {textValue = "否";}} else if (value instanceof Date) {Date date = (Date) value;SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");textValue = sdf.format(date);} elsetextValue = value.toString();return textValue;}}
啦啦啦
啦啦啦
Java Annotation 应用 -- 导出Excel表格相关推荐
- java使用模板导出Excel表格
java使用模板导出Excel表格 文章目录 java使用模板导出Excel表格 模板示例 一.引入依赖 二.使用步骤 1.添加工具类 2.导出Excel 模板示例 一.引入依赖 <depend ...
- java中poi导出Excel表格(前台流文件接收)
java中poi导出Excel表格,前端以流的方式接收,而非直接生成文件再下载,解决多台服务器部署后,路径地址不统一导致的下载问题. 生成Excel示例图: 2.代码说明 ① 在上次的基础上增加了底部 ...
- java代码实现导出Excel表格、工具ssm框架、maven、idea
第一步.导入依赖 <!--生成excel文件--><dependency><groupId>org.apache.poi</groupId><ar ...
- java多表头导出excel表格_【每日一点】1. Java如何实现导出Excel单表头或多表头
一.背景 在后台项目中,经常会遇到将呈现的内容导出到Excel的需求,通过都是导出单个表头的Excel文件,如果存在级联关系的情况下,也就需要导出多表头的场景.今天这篇文章就是分享导出Excel单表头 ...
- java导出excel float_【Java】导入导出Excel表格
1.将excel导入到内存 1. 调用工作簿Workbook的静态方法getWorkbook(),获得工作簿Workbook对象 InputStream in = new FileInputStrea ...
- java io导出excel表格_Java IO 导入导出Excel表格
1.将excel导入到内存 1. 调用工作簿Workbook的静态方法getWorkbook(),获得工作簿Workbook对象 InputStream in = new FileInputStrea ...
- java 导入导出excel表格
java 导入导出excel表格 业务上有需求上传excel表格并读取内容,本文记录一下该方法 表格导入 引入相应的工具包 <dependency><groupId>cn.af ...
- 简单的 Java 导出 Excel 表格 小例子《一抹茶CSDN》
Java 导出 Excel 为什么要有导出Excel表格的功能呢? 因为我们在使用软件时会有,一些数据需要导出来,进行留存,大多数人使用的都是office的办公软件,就会使用常用的Excel表格.因此 ...
- java 导出excel教程_Java导出Excel表格
Java导出Excel表格 导出Excel表格需要一个poi-3.9.jar的包,该包在网上可以找到. 第一步,创建Excel对象. HSSFWorkbook workbook = new HSSFW ...
最新文章
- DreamWeaver文件保存时,提示发生共享违例问题的解决方法
- CDO/CDS与次贷危机
- Juniper EX3400 Rescue configuration is not set
- python爬取mysql_Python如何爬取51cto数据并存入MySQL
- mysql Partition(分区)初探
- javascript-内置对象-date对象-JSON对象-Math对象
- 深度学习(五十八)caffe移植至mxnet
- 送给测试行业年轻人们的一些建议
- 娱乐篇第十期:互联网的事情you意思(十)
- Spark2.1.0模型设计与基本架构(下)
- FishC笔记—33 讲 异常处理:你不可能总是对的2
- php测速,speedtest-x :一款PHP网页测速工具
- C# DataGridView 冻结列或行
- 20201216指数估值表
- php自动化营销推广引流源码,PHP自动化售货发卡网源码
- MySQL SUM()函数按条件求和
- python中常用英语口语_常用英语口语100句超实用-
- SuperMap iDesktop 操作入门(一)创建文件型工作空间
- 使用Packer在Winodws VMware Workstation Pro上自动部署Windows Server 2016中文版
- c语言open()介绍
热门文章
- AdaIN(Arbitrary Style Transfer in Real-time with Adaptive Instance Normalization)——论文阅读
- 英寸与毫米的换算依据
- 南邮——计算机图像学——会动的立方体(变换)
- 点云深度学习系列博客(二): 点云配准网络PCRNet
- 关于德鲁伊数据源配置的记录
- HTML页面查看world等文件,网页文件 - HTML - 网页基础 - KK的小故事
- 解除文件占用,解决文件被占用不能删除
- RSA加密算法-非对称加密算法的使用
- 有discuz数据库,忘了管理员密码,怎样进后台
- ProtoPie 学习