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>();
// 遍历整个filed
for (int i = 0; i < filed.length; i++) {
Field f = filed[i];
ExcelAnnotation exa = f.getAnnotation(ExcelAnnotation.class);
// 如果设置了annottion
if (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>();
// 遍历整个filed
for (int i = 0; i < filed.length; i++) {
Field f = filed[i];
ExcelAnnotation exa = f.getAnnotation(ExcelAnnotation.class);
// 如果设置了annottion
if (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);
} else
textValue = value.toString(); return textValue;
} }
啦啦啦
啦啦啦
Java Annotation 应用 -- 导出Excel表格的更多相关文章
- Java代码导入导出 Excel 表格最简单的方法
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStrea ...
- Java IO 导入导出Excel表格
1.将excel导入到内存 1. 调用工作簿Workbook的静态方法getWorkbook(),获得工作簿Workbook对象 InputStream in = new FileInputStrea ...
- java基础篇 -- 导出excel表格数据
本篇文章基于java把数据库中的数据以Excel的方式导出,欢迎各位大神吐槽: 1.基于maven jar包引入如下: <dependency> <groupId>net.so ...
- java使用jxls导出Excel
jxls是基于POI的Excel模板导出导入框架.通过使用类似于jstl的标签,有效较少导出Excel的代码量. 1.pom <!-- https://mvnrepository.com/art ...
- java导出excel表格
java导出excel表格: 1.导入jar包 <dependency> <groupId>org.apache.poi</groupId> <artifac ...
- java 实现用户自由选择字段实现导出EXCEL表格
package com.thinkgem.jeesite.common.utils.excel; import java.io.File; import java.io.OutputStream; i ...
- java中使用jxl导出Excel表格详细通用步骤
该方法一般接收两个参数,response和要导出的表格内容的list. 一般我们将数据库的数据查询出来在页面进行展示,根据用户需求,可能需要对页面数据进行导出. 此时只要将展示之前查询所得的数据放入s ...
- Spring Boot 导出Excel表格
Spring Boot 导出Excel表格 添加支持 <!--添加导入/出表格依赖--> <dependency> <groupId>org.apache.poi& ...
- Java之POI导出Excel(一):单sheet
相信在大部分的web项目中都会有导出导入Excel的需求,今天我们就来看看如何用Java代码去实现 用POI导出Excel表格. 一.pom引用 pom文件中,添加以下依赖 查看代码 <!-- ...
随机推荐
- 基于Python的SQLAlchemy的操作
安装 在Python使用SQLAlchemy的首要前提是安装相应的模块,当然作为python的优势,可以到python安装目录下的scripts下,同时按住shift+加上鼠标左键,从而在菜单中打开命 ...
- Qt开发的程序在没有安装Qt环境的机器上可能出现的一些问题
Qt开发的程序在没有安装Qt环境的机器上可能出现的一些问题,如:除png外的其它类型的图片,如:jpg.ico.bmp等,还有中文乱码等问题,出现这些问题的本质是Qt对这类文件格式或编码格式的支持方式 ...
- 查看 Mac/Linux 某端口占用情况
Mac/Linux 平台下,通用命令: lsof -i:8080 (8080 为 端口号,根据需要,替换为其他端口号) 可以查看该端口被什么程序占用,并显示 pid,方便 kill 掉 Linux如 ...
- vue_axios请求封装、异常拦截统一处理
1.前端网络请求封装.异常统一处理 vue中采用axios处理网络请求,避免请求接口重复代码,以及各种网络情况造成的异常情况的判断,采用axios请求封装和异常拦截操作: axios 请求封装 // ...
- kubeadm安装kubernetes V1.11.1 集群
之前测试了离线环境下使用二进制方法安装配置Kubernetes集群的方法,安装的过程中听说 kubeadm 安装配置集群更加方便,因此试着折腾了一下.安装过程中,也有一些坑,相对来说操作上要比二进制方 ...
- Spring Boot异常处理
一.默认映射 我们在做Web应用的时候,请求处理过程中发生错误是非常常见的情况.Spring Boot提供了一个默认的映射:/error,当处理中抛出异常之后,会转到该请求中处理,并且该请求有一个全局 ...
- 《A.I.爱》王力宏与人工智能谈恋爱 邀李开复来客串
2017年9月19日下午,王力宏首张数字专辑<A.I.爱>亚洲发布会在北京举行,力宏在新歌MV中化身技术男,网红机器人Sophia扮新娘!和Robo Alpha机器人天团大跳舞蹈,与超跑酷 ...
- 树莓派3中安装JDK
一.简介 树莓派3(Raspbian系统,下载地址:https://www.raspberrypi.org/downloads/raspbian/),安装JDK8,直接运行:apt-get insta ...
- storm杂谈之Why use netty as transport instead of zeromq
Storm后来用Netty来代替了zmq,这个能够參考一下两篇blog 这两篇blog具体的阐述原因以及一些性能測试, 大家參考一下 Reference 1.Netty 4 Reduces GC Ov ...
- grep 多行 正则匹配
https://stackoverflow.com/questions/2686147/how-to-find-patterns-across-multiple-lines-using-grep I ...