使用POI和Java反射机制导出数据到excel

版权声明:本文为原创文章,转载请注明转自Clement-Xu的csdn博客。 https://blog.csdn.net/ClementAD/article/details/42120009
                                        <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-e2445db1a8.css">
                    <div class="htmledit_views">

下面以导出2007(文件名后缀为:xlsx)格式的excel文件为例,简单介绍利用Java反射机制自由地读取数据并填充到excel中的过程。


第一步:引入依赖包(2007版本的excel依赖包为poi-ooxml,如果是2003的则为poi)


  
  
  1. <dependency>
  2. <groupId>org.apache.poi </groupId>
  3. <artifactId>poi-ooxml </artifactId>
  4. <version>3.10.1 </version>
  5. </dependency>

第二步:定义一个用于保存数据的实体类

注意getSexName()方法的用法。


  
  
  1. package com.xjj.poi;
  2. import java.util.Date;
  3. public class Student {
  4. private long id;
  5. private String name;
  6. private int age;
  7. private boolean sex;
  8. private Date birthday;
  9. public Student() {
  10. }
  11. public Student(long id, String name, int age, boolean sex, Date birthday) {
  12. this.id = id;
  13. this.name = name;
  14. this.age = age;
  15. this.sex = sex;
  16. this.birthday = birthday;
  17. }
  18. //sex转换为中文
  19. public String getSexName(){
  20. return (sex== true) ? "男" : "女";
  21. }
  22. public long getId() {
  23. return id;
  24. }
  25. public void setId(long id) {
  26. this.id = id;
  27. }
  28. public String getName() {
  29. return name;
  30. }
  31. public void setName(String name) {
  32. this.name = name;
  33. }
  34. public int getAge() {
  35. return age;
  36. }
  37. public void setAge(int age) {
  38. this.age = age;
  39. }
  40. public boolean getSex() {
  41. return sex;
  42. }
  43. public void setSex(boolean sex) {
  44. this.sex = sex;
  45. }
  46. public Date getBirthday() {
  47. return birthday;
  48. }
  49. public void setBirthday(Date birthday) {
  50. this.birthday = birthday;
  51. }
  52. }

第三步:利用Java反射机制把数据填入excel workbook中并测试输出到一个文件。具体步骤请看代码注释。测试例子中,可以自由的决定需要读取实体类Student中的哪些属性到excel中。


  
  
  1. package com.xjj.util;
  2. import java.awt.Color;
  3. import java.io.FileNotFoundException;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.io.OutputStream;
  7. import java.lang.reflect.Method;
  8. import java.text.SimpleDateFormat;
  9. import java.util.ArrayList;
  10. import java.util.Collection;
  11. import java.util.Date;
  12. import java.util.LinkedHashMap;
  13. import java.util.List;
  14. import org.apache.poi.ss.usermodel.IndexedColors;
  15. import org.apache.poi.ss.usermodel.Workbook;
  16. import org.apache.poi.xssf.usermodel.XSSFCell;
  17. import org.apache.poi.xssf.usermodel.XSSFCellStyle;
  18. import org.apache.poi.xssf.usermodel.XSSFColor;
  19. import org.apache.poi.xssf.usermodel.XSSFFont;
  20. import org.apache.poi.xssf.usermodel.XSSFRichTextString;
  21. import org.apache.poi.xssf.usermodel.XSSFRow;
  22. import org.apache.poi.xssf.usermodel.XSSFSheet;
  23. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  24. import com.xjj.poi.Student;
  25. public class ExcelUtil {
  26. /**
  27. * 根据输入的数据生成一个XSSFWorkbook
  28. * @param title:sheet名称
  29. * @param propertyHeaderMap:<property, header>(<T中的property名称、有getter就行, 对应显示在Excel sheet中的列标题>)
  30. * 用LinkedHashMap保证读取的顺序和put的顺序一样
  31. * @param dataSet:实体类集合
  32. * @return:XSSFWorkbook
  33. */
  34. public static <T> XSSFWorkbook generateXlsxWorkbook(String title, LinkedHashMap<String, String> propertyHeaderMap, Collection<T> dataSet) {
  35. // 声明一个工作薄
  36. XSSFWorkbook workbook = new XSSFWorkbook();
  37. // 生成一个表格
  38. XSSFSheet sheet = workbook.createSheet(title);
  39. // 设置表格默认列宽度为15个字节
  40. sheet.setDefaultColumnWidth(( int) 15);
  41. XSSFCellStyle headerStyle = getHeaderStyle(workbook);
  42. XSSFCellStyle contentStyle = getContentStyle(workbook);
  43. // 生成表格标题行
  44. XSSFRow row = sheet.createRow( 0);
  45. int i = 0;
  46. for(String key : propertyHeaderMap.keySet()){
  47. XSSFCell cell = row.createCell(i);
  48. cell.setCellStyle(headerStyle);
  49. XSSFRichTextString text = new XSSFRichTextString(propertyHeaderMap.get(key));
  50. cell.setCellValue(text);
  51. i++;
  52. }
  53. //循环dataSet,每一条对应一行
  54. int index = 0;
  55. for(T data : dataSet){
  56. index ++;
  57. row = sheet.createRow(index);
  58. int j = 0;
  59. for(String property : propertyHeaderMap.keySet()){
  60. XSSFCell cell = row.createCell(j);
  61. cell.setCellStyle(contentStyle);
  62. //拼装getter方法名
  63. String getMethodName = "get" + property.substring( 0, 1).toUpperCase() + property.substring( 1);
  64. try {
  65. //利用反射机制获取dataSet中的属性值,填进cell中
  66. Class<? extends Object> tCls = data.getClass();
  67. Method getMethod = tCls.getMethod(getMethodName, new Class[] {});
  68. Object value = getMethod.invoke(data, new Object[] {}); //调用getter从data中获取数据
  69. // 判断值的类型后进行类型转换
  70. String textValue = null;
  71. if (value instanceof Date) {
  72. Date date = (Date) value;
  73. SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd");
  74. textValue = sdf.format(date);
  75. } else {
  76. // 其它数据类型都当作字符串简单处理
  77. textValue = value.toString();
  78. }
  79. /*if(textValue != null){
  80. Pattern p = Pattern.compile("^//d+(//.//d+)?$");
  81. Matcher matcher = p.matcher(textValue);
  82. if (matcher.matches()) {
  83. // 是数字当作double处理
  84. cell.setCellValue(Double.parseDouble(textValue));
  85. } else {
  86. XSSFRichTextString richString = new XSSFRichTextString(textValue);
  87. cell.setCellValue(richString);
  88. }
  89. }*/
  90. XSSFRichTextString richString = new XSSFRichTextString(textValue);
  91. cell.setCellValue(richString);
  92. } catch (Exception e) {
  93. e.printStackTrace();
  94. }
  95. j++;
  96. }
  97. }
  98. return workbook;
  99. }
  100. /**
  101. * 生成一个标题style
  102. * @return style
  103. */
  104. public static XSSFCellStyle getHeaderStyle(Workbook workbook){
  105. return getHeaderStyle(workbook, Color.BLUE, IndexedColors.WHITE.getIndex());
  106. }
  107. /**
  108. * 生成一个指定颜色的标题style
  109. * @param workbook
  110. * @param foregroundColor
  111. * @param fontColor
  112. * @return
  113. */
  114. public static XSSFCellStyle getHeaderStyle(Workbook workbook, Color foregroundColor, short fontColor){
  115. // 生成一个样式(用于标题)
  116. XSSFCellStyle style = (XSSFCellStyle) workbook.createCellStyle();
  117. // 设置这些样式
  118. style.setFillForegroundColor( new XSSFColor(foregroundColor));
  119. style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
  120. style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
  121. style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
  122. style.setBorderRight(XSSFCellStyle.BORDER_THIN);
  123. style.setBorderTop(XSSFCellStyle.BORDER_THIN);
  124. style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
  125. // 生成一个字体
  126. XSSFFont font = (XSSFFont) workbook.createFont();
  127. font.setColor(fontColor);
  128. font.setFontHeightInPoints(( short) 12);
  129. font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
  130. // 把字体应用到当前的样式
  131. style.setFont(font);
  132. return style;
  133. }
  134. /**
  135. * 生成一个用于内容的style
  136. * @param workbook
  137. * @return
  138. */
  139. public static XSSFCellStyle getContentStyle(Workbook workbook){
  140. // 生成并设置另一个样式(用于内容)
  141. XSSFCellStyle style = (XSSFCellStyle) workbook.createCellStyle();
  142. //style.setFillForegroundColor(new XSSFColor(Color.YELLOW));
  143. //style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
  144. style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
  145. style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
  146. style.setBorderRight(XSSFCellStyle.BORDER_THIN);
  147. style.setBorderTop(XSSFCellStyle.BORDER_THIN);
  148. style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
  149. style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
  150. // 生成另一个字体
  151. XSSFFont font = (XSSFFont) workbook.createFont();
  152. font.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
  153. // 把字体应用到当前的样式
  154. style.setFont(font);
  155. return style;
  156. }
  157. //测试:
  158. public static void main(String[] args) {
  159. List<Student> dataSet = new ArrayList<Student>();
  160. dataSet.add( new Student( 10000001, "张三", 20, true, new Date()));
  161. dataSet.add( new Student( 20000002, "李丽", 24, false, new Date()));
  162. dataSet.add( new Student( 30000003, "王五", 22, true, new Date()));
  163. LinkedHashMap<String, String> propertyHeaderMap = new LinkedHashMap<>();
  164. //propertyHeaderMap.put("id", "唯一标识"); //注释掉,不导出id
  165. propertyHeaderMap.put( "name", "姓名");
  166. propertyHeaderMap.put( "age", "年龄");
  167. propertyHeaderMap.put( "sexName", "性别"); //直接获取Student中的sexName,而不是sex
  168. propertyHeaderMap.put( "birthday", "生日");
  169. try {
  170. XSSFWorkbook ex = ExcelUtil.generateXlsxWorkbook( "测试tab", propertyHeaderMap, dataSet);
  171. OutputStream out = new FileOutputStream( "F://student3.xlsx");
  172. ex.write(out);
  173. System.out.println( "导出成功!");
  174. } catch (FileNotFoundException e) {
  175. e.printStackTrace();
  176. } catch (IOException e) {
  177. e.printStackTrace();
  178. }
  179. }
  180. }

测试结果(性别已经自动转换为中文):

姓名年龄性别生日
张三202014-12-24
李丽242014-12-24
王五222014-12-24


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值