相关知识链接:

  Introspector(内省)

  POI

  

1.声明注解

  1. package com.ciic.component.excel;
  2.  
  3. import java.lang.annotation.ElementType;
  4. import java.lang.annotation.Retention;
  5. import java.lang.annotation.RetentionPolicy;
  6. import java.lang.annotation.Target;
  7.  
  8. /**
  9. *
  10. */
  11. @Retention(RetentionPolicy.RUNTIME)
  12. @Target(ElementType.FIELD)
  13. public @interface ExcelAnnotation {
  14. // excel导出时标题显示的名字,如果没有设置Annotation属性,将不会被导出和导入
  15. public String exportName();
  16. }

2.应用注解

  1. package com.ciic.history.entity;
  2.  
  3. import com.ciic.component.excel.ExcelAnnotation;
  4. import com.ciic.history.common.ExportBase;
  5.  
  6. //客户一揽子表
  7. public class EsinnerLimeCustomerPreviewIndex extends ExportBase {
  8. @ExcelAnnotation(exportName = "客户名称")
  9. private String imscustomername;
  10. @ExcelAnnotation(exportName = "客户编号")
  11. private String imscustomercode;
  12. @ExcelAnnotation(exportName = "合同方式")
  13. private long imscontracttypea;
  14. @ExcelAnnotation(exportName = "月服务费")
  15. private String serviceimstotalfee;
  16. @ExcelAnnotation(exportName = "雇员人数")
  17. private long employeecount;
  18. @ExcelAnnotation(exportName = "应收金额")
  19. private String imstotalfee;
  20. @ExcelAnnotation(exportName = "实收金额")
  21. private String doneimstotalfee;
  22. @ExcelAnnotation(exportName = "应付金额")
  23. private String imssocialinsurancetfee;
  24. @ExcelAnnotation(exportName = "实付金额")
  25. private String dtlimssocialinsurancetfee;
  26. @ExcelAnnotation(exportName = "最后修改日期")
  27. private String modifieddate;
  28. @ExcelAnnotation(exportName = "客户简称")
  29. private String imscustomershort;
  30. @ExcelAnnotation(exportName = "合作方式")
  31. private long imscontracttypeb;
  32. @ExcelAnnotation(exportName = "客户经理")
  33. private String imscustomerclerk;
  34. @ExcelAnnotation(exportName = "未付款日期")
  35. private String unimspaynoticemonth;
  36. @ExcelAnnotation(exportName = "已交付日期")
  37. private String doneimspaynoticemonth;
  38.  
  39. getter()
  40. setter()
  41. }

3.解析注解

  3.1 获取数据

  1. public void exportCustomerPreview(EsinnerLimeCustomerPreviewIndex customerPreview, HttpServletResponse response)throws Exception{
  2.  
  3. JsonEntity entity =XAServiceL.customerPreviewSearch(customerPreview,customerPreview.getPage(),customerPreview.getRows());
  4.  
  5. ExcelExport excelExport= new ExcelExport();
  6. response.reset();
  7. String fileName="";
  8. if(StringUtils.isBlank(customerPreview.getExcelName())){
  9. fileName="客户一揽子表/第"+customerPreview.getPage()+"页.xls";
  10. }else{
  11. fileName=customerPreview.getExcelName()+"/第"+customerPreview.getPage()+"页.xls";
  12. }
  13.  
  14. response.setContentType("application/form-data;charset=UTF-8");
  15. response.addHeader("Content-Disposition", "attachment;filename=\""
  16. + new String(fileName.getBytes("UTF-8"),
  17. "UTF-8") + "\"");
  18. System.out.println(Arrays.toString(entity.getRows().toArray()));
  19. List<EsinnerLimeCustomerPreviewIndex> outExcel=new ArrayList<EsinnerLimeCustomerPreviewIndex>();
  20. for(int i=0;i<entity.getRows().size();i++){
  21. outExcel.add(MapBeanConvert.toBean(EsinnerLimeCustomerPreviewIndex.class,(Map) entity.getRows().get(i)));
  22. }
  23. excelExport.exportExcel(customerPreview.getExcelName(),outExcel,response.getOutputStream());
  24. }

  3.2 解析注解

  1. /**
  2. * 将一个 Map 对象转化为一个 JavaBean
  3. *
  4. * @param clazz 要转化的类型
  5. * @param map 包含属性值的 map
  6. * @return 转化出来的 JavaBean 对象
  7. * @throws IntrospectionException 如果分析类属性失败
  8. * @throws IllegalAccessException 如果实例化 JavaBean 失败
  9. * @throws InstantiationException 如果实例化 JavaBean 失败
  10. * @throws InvocationTargetException 如果调用属性的 setter 方法失败
  11. */
  12. @SuppressWarnings("rawtypes")
  13. public static <T> T toBean(Class<T> clazz, Map map) {
  14. T obj = null;
  15. String name = "";
  16. try {
  17. BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
  18. obj = clazz.newInstance(); // 创建 JavaBean 对象
  19.  
  20. // 给 JavaBean 对象的属性赋值
  21. PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
  22. for (int i = 0; i < propertyDescriptors.length; i++) {
  23. PropertyDescriptor descriptor = propertyDescriptors[i];
  24. String propertyName = descriptor.getName();
  25. name = propertyName;
  26. if (map.containsKey(propertyName)) {
  27. // 下面一句可以 try 起来,这样当一个属性赋值失败的时候就不会影响其他属性赋值。
  28. Object value = map.get(propertyName);
  29. if ("".equals(value)) {
  30. value = null;
  31. }
  32. Object[] args = new Object[1];
  33. args[0] = value;
  34. try {
  35. descriptor.getWriteMethod().invoke(obj, args);
  36. } catch (InvocationTargetException e) {
  37. System.out.println("字段映射失败");
  38. }
  39. }
  40. }
  41. } catch (IllegalAccessException e) {
  42. System.out.println("实例化 JavaBean 失败");
  43. } catch (IntrospectionException e) {
  44. System.out.println("分析类属性失败");
  45. } catch (IllegalArgumentException e) {
  46. // e.printStackTrace();
  47. System.err.println(name);
  48. System.out.println("映射错误");
  49. } catch (InstantiationException e) {
  50. System.out.println("实例化 JavaBean 失败");
  51. }
  52. return (T) obj;
  53. }

  3.3 导出Excel

  1. package com.ciic.component.excel;
  2.  
  3. import org.apache.poi.hssf.usermodel.*;
  4.  
  5. import java.io.File;
  6. import java.io.FileOutputStream;
  7. import java.io.IOException;
  8. import java.io.OutputStream;
  9. import java.lang.reflect.Field;
  10. import java.lang.reflect.Method;
  11. import java.text.SimpleDateFormat;
  12. import java.util.*;
  13.  
  14. /**
  15. *
  16. */
  17. public class ExcelExport<T> {
  18. /**
  19. * @param title 标题
  20. * @param dataset 集合
  21. * @param out 输出流
  22. */
  23. public void exportExcel(String title, Collection<T> dataset,
  24. OutputStream out) {
  25. // 声明一个工作薄
  26. try {
  27. //首先检查数据看是否是正确的
  28. Iterator<T> its = dataset.iterator();
  29. if (dataset == null || !its.hasNext() || title == null || out == null) {
  30. throw new Exception("传入的数据不对!");
  31. }
  32.  
  33. T ts = (T) its.next();
  34.  
  35. HSSFWorkbook workbook = new HSSFWorkbook();
  36. // 生成一个表格
  37. HSSFSheet sheet = workbook.createSheet(title);
  38. // 设置表格默认列宽度为15个字节
  39. sheet.setDefaultColumnWidth(15);
  40. // 生成一个样式
  41. HSSFCellStyle style = workbook.createCellStyle();
  42. // 设置标题样式
  43. // style = ExcelStyle.setHeadStyle(workbook, style);
  44. // // 生成并设置主体样式
  45. // HSSFCellStyle style2 = workbook.createCellStyle();
  46. // style2 = ExcelStyle.setbodyStyle(workbook, style2);
  47. // 得到所有字段
  48.  
  49. Field filed[] = ts.getClass().getDeclaredFields();
  50. // 标题
  51. List<String> exportfieldtile = new ArrayList<String>();
  52. // 导出的字段
  53. List<String> fiedName = new ArrayList<String>();
  54. // 遍历整个filed
  55. for (int i = 0; i < filed.length; i++) {
  56. Field f = filed[i];
  57. ExcelAnnotation exa = f.getAnnotation(ExcelAnnotation.class);
  58. // 如果设置了annottion
  59. if (exa != null) {
  60. String exprot = exa.exportName();
  61. // 添加到标题
  62. exportfieldtile.add(exprot);
  63. // 添加到需要导出的字段
  64. fiedName.add(f.getName());
  65. }
  66. }
  67. // 产生表格标题行
  68. HSSFRow row = sheet.createRow(0);
  69. for (int i = 0; i < exportfieldtile.size(); i++) {
  70. HSSFCell cell = row.createCell(i);
  71. cell.setCellStyle(style);
  72. HSSFRichTextString text = new HSSFRichTextString(
  73. exportfieldtile.get(i));
  74. cell.setCellValue(text);
  75. }
  76.  
  77. Iterator<T> it = dataset.iterator();
  78. int index = 0;
  79. // 循环整个集合
  80. while (it.hasNext()) {
  81. index++;
  82. row = sheet.createRow(index);
  83. T t = (T) it.next();
  84. for (int k = 0; k < fiedName.size(); k++) {
  85. HSSFCell cell = row.createCell(k);
  86. String fieldname = fiedName.get(k);
  87. String getMethodName = "get"
  88. + fieldname.substring(0, 1).toUpperCase()
  89. + fieldname.substring(1);
  90. Class tCls = t.getClass();
  91. Method getMethod = tCls.getMethod(getMethodName,
  92. new Class[]{});
  93. Object value = getMethod.invoke(t, new Object[]{});
  94.  
  95. String textValue = getValue(value);
  96.  
  97. HSSFRichTextString richString = new HSSFRichTextString(
  98. textValue);
  99. cell.setCellValue(richString);
  100. }
  101.  
  102. }
  103. workbook.write(out);
  104. } catch (Exception e) {
  105. e.printStackTrace();
  106. }
  107.  
  108. }
  109.  
  110. /**
  111. * @param title 标题
  112. * @param dataset 集合
  113. */
  114. public File exportExcel(String title, Collection<T> dataset) {
  115. OutputStream out = null;
  116. File file = null;
  117. // 声明一个工作薄
  118. try {
  119. //首先检查数据看是否是正确的
  120. Iterator<T> its = dataset.iterator();
  121. if (dataset == null || !its.hasNext() || title == null) {
  122. throw new Exception("传入的数据不对!");
  123. }
  124.  
  125. T ts = (T) its.next();
  126.  
  127. HSSFWorkbook workbook = new HSSFWorkbook();
  128. // 生成一个表格
  129. HSSFSheet sheet = workbook.createSheet(title);
  130. // 设置表格默认列宽度为15个字节
  131. sheet.setDefaultColumnWidth(15);
  132. // 生成一个样式
  133. HSSFCellStyle style = workbook.createCellStyle();
  134. // 设置标题样式
  135. // style = ExcelStyle.setHeadStyle(workbook, style);
  136. // // 生成并设置主体样式
  137. // HSSFCellStyle style2 = workbook.createCellStyle();
  138. // style2 = ExcelStyle.setbodyStyle(workbook, style2);
  139. // 得到所有字段
  140.  
  141. Field filed[] = ts.getClass().getDeclaredFields();
  142. // 标题
  143. List<String> exportfieldtile = new ArrayList<String>();
  144. // 导出的字段
  145. List<String> fiedName = new ArrayList<String>();
  146. // 遍历整个filed
  147. for (int i = 0; i < filed.length; i++) {
  148. Field f = filed[i];
  149. ExcelAnnotation exa = f.getAnnotation(ExcelAnnotation.class);
  150. // 如果设置了annottion
  151. if (exa != null) {
  152. String exprot = exa.exportName();
  153. // 添加到标题
  154. exportfieldtile.add(exprot);
  155. // 添加到需要导出的字段
  156. fiedName.add(f.getName());
  157. }
  158. }
  159. // 产生表格标题行
  160. HSSFRow row = sheet.createRow(0);
  161. for (int i = 0; i < exportfieldtile.size(); i++) {
  162. HSSFCell cell = row.createCell(i);
  163. cell.setCellStyle(style);
  164. HSSFRichTextString text = new HSSFRichTextString(
  165. exportfieldtile.get(i));
  166. cell.setCellValue(text);
  167. }
  168.  
  169. Iterator<T> it = dataset.iterator();
  170. int index = 0;
  171. // 循环整个集合
  172. while (it.hasNext()) {
  173. index++;
  174. row = sheet.createRow(index);
  175. T t = (T) it.next();
  176. for (int k = 0; k < fiedName.size(); k++) {
  177. HSSFCell cell = row.createCell(k);
  178. String fieldname = fiedName.get(k);
  179. String getMethodName = "get"
  180. + fieldname.substring(0, 1).toUpperCase()
  181. + fieldname.substring(1);
  182. Class tCls = t.getClass();
  183. Method getMethod = tCls.getMethod(getMethodName,
  184. new Class[]{});
  185. Object value = getMethod.invoke(t, new Object[]{});
  186.  
  187. String textValue = getValue(value);
  188.  
  189. HSSFRichTextString richString = new HSSFRichTextString(
  190. textValue);
  191. cell.setCellValue(richString);
  192. }
  193.  
  194. }
  195. file = new File("/tmp/testOne.xls");
  196. out = new FileOutputStream(file);
  197. workbook.write(out);
  198. } catch (Exception e) {
  199. e.printStackTrace();
  200. } finally {
  201. try {
  202. if (out != null) {
  203. out.close();
  204. }
  205. } catch (IOException e) {
  206. e.printStackTrace();
  207. }
  208. }
  209. return file;
  210. }
  211.  
  212. private String getValue(Object value) {
  213. String textValue = "";
  214. if (value == null)
  215. return textValue;
  216.  
  217. if (value instanceof Boolean) {
  218. boolean bValue = (Boolean) value;
  219. textValue = "是";
  220. if (!bValue) {
  221. textValue = "否";
  222. }
  223. } else if (value instanceof Date) {
  224. Date date = (Date) value;
  225. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  226. textValue = sdf.format(date);
  227. } else
  228. textValue = value.toString();
  229.  
  230. return textValue;
  231. }
  232.  
  233. }

啦啦啦

啦啦啦

Java Annotation 应用 -- 导出Excel表格的更多相关文章

  1. Java代码导入导出 Excel 表格最简单的方法

    import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStrea ...

  2. Java IO 导入导出Excel表格

    1.将excel导入到内存 1. 调用工作簿Workbook的静态方法getWorkbook(),获得工作簿Workbook对象 InputStream in = new FileInputStrea ...

  3. java基础篇 -- 导出excel表格数据

    本篇文章基于java把数据库中的数据以Excel的方式导出,欢迎各位大神吐槽: 1.基于maven jar包引入如下: <dependency> <groupId>net.so ...

  4. java使用jxls导出Excel

    jxls是基于POI的Excel模板导出导入框架.通过使用类似于jstl的标签,有效较少导出Excel的代码量. 1.pom <!-- https://mvnrepository.com/art ...

  5. java导出excel表格

    java导出excel表格: 1.导入jar包 <dependency> <groupId>org.apache.poi</groupId> <artifac ...

  6. java 实现用户自由选择字段实现导出EXCEL表格

    package com.thinkgem.jeesite.common.utils.excel; import java.io.File; import java.io.OutputStream; i ...

  7. java中使用jxl导出Excel表格详细通用步骤

    该方法一般接收两个参数,response和要导出的表格内容的list. 一般我们将数据库的数据查询出来在页面进行展示,根据用户需求,可能需要对页面数据进行导出. 此时只要将展示之前查询所得的数据放入s ...

  8. Spring Boot 导出Excel表格

    Spring Boot 导出Excel表格 添加支持 <!--添加导入/出表格依赖--> <dependency> <groupId>org.apache.poi& ...

  9. Java之POI导出Excel(一):单sheet

    相信在大部分的web项目中都会有导出导入Excel的需求,今天我们就来看看如何用Java代码去实现 用POI导出Excel表格. 一.pom引用 pom文件中,添加以下依赖 查看代码  <!-- ...

随机推荐

  1. AngularJS自定义Directive中link和controller的区别

    在AngularJS中,自定义Directive过程中,有时用link和controller都能实现相同的功能.那么,两者有什么区别呢? 使用link函数的Directive 页面大致是: <b ...

  2. Mui 下拉刷新,刷新完成功能实现

    Mui中,正在刷新后,就直接回弹了,没有刷新完成这个过程,然后我就在中间添加了一个过程.   代码如下:   //-----------日期格式化------------- function form ...

  3. JavaScript性能优化小知识总结

    原文出处: YouYaInsist   欢迎分享原创到伯乐头条 前言 一直在学习javascript,也有看过<犀利开发Jquery内核详解与实践>,对这本书的评价只有两个字犀利,可能是对 ...

  4. leetcode笔记:Validate Binary Search Tree

    一. 题目描写叙述 Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is ...

  5. Android——进程通信/ AIDL/Message相关知识总结贴

    Android多进程通信 http://www.apkbus.com/android-83462-1-1.html Android 跨进程通信(一) http://www.apkbus.com/and ...

  6. 腾讯企业邮箱设置发送邮件的配置(针对smtp)

    QQ邮箱也是如下配置,不过需要进行开启smtp

  7. [Android App]IFCTT,即:If Copy Then That,一个基于IFTTT的"This"实现

    IFCTT,即:If Copy Then That,是一个基于IFTTT(If This Then That)的"This"实现,它打通了"用户手机端操作"与& ...

  8. 图文剖析自己定义View的绘制(以自己定义滑动button为例)

    自己定义View一直是横在Android开发人员面前的一道坎. 一.View和ViewGroup的关系 从View和ViewGroup的关系来看.ViewGroup继承View. View的子类.多是 ...

  9. HTML5学习笔记(二十八):跨域

    在跨域安全性方面,有多个地方会有限制,主要是XMLHttpRequest对象的跨域限制和iFrame的跨域限制,下面我们分别来看一下. Ajax跨域(CORS) CORS是一个W3C标准,全称是&qu ...

  10. [转]新人常识普及:我们为什么必须会git和maven

    转自贴吧:http://tieba.baidu.com/p/3458400116 鉴于本吧多新人,新人又需要多交流才能进步,今天就给新人们讲讲git和maven的必要性,因为,他们的重要性,远远超过很 ...