poiutil.java 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. package com.steerinfo.dil.util;
  2. import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
  3. import com.beust.jcommander.internal.Lists;
  4. import com.google.common.collect.Maps;
  5. import com.steerinfo.framework.utils.collection.MapUtils;
  6. import org.apache.poi.ss.usermodel.*;
  7. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  8. import javax.servlet.ServletOutputStream;
  9. import javax.servlet.http.HttpServletResponse;
  10. import java.io.*;
  11. import java.lang.reflect.Method;
  12. import java.nio.charset.StandardCharsets;
  13. import java.util.*;
  14. //导出excle工具类
  15. public class poiutil {
  16. private final static String xls = "xls";
  17. private final static String xlsx = "xlsx";
  18. private final static String DATE_FORMAT = "yyyy/MM/dd";
  19. //参数说明: fileName:文件名 projects:对象集合 columnNames: 列名 keys: map中的key
  20. public static void start_download(HttpServletResponse response, String fileName, List<?> projects, String[] columnNames, String[] keys) throws IOException {
  21. //将集合中对象的属性 对应到 List<Map<String,Object>>
  22. List<Map<String, Object>> list = createExcelRecord(projects, keys);
  23. ByteArrayOutputStream os = new ByteArrayOutputStream();
  24. try {
  25. //将转换成的Workbook对象通过流形式下载
  26. createWorkBook(list, keys, columnNames).write(os);
  27. } catch (IOException e) {
  28. e.printStackTrace();
  29. }
  30. byte[] content = os.toByteArray();
  31. InputStream is = new ByteArrayInputStream(content);
  32. // 设置response参数,可以打开下载页面
  33. response.reset();
  34. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  35. response.setCharacterEncoding("utf-8");
  36. response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xlsx").getBytes(), StandardCharsets.ISO_8859_1));
  37. ServletOutputStream out = response.getOutputStream();
  38. BufferedInputStream bis = null;
  39. BufferedOutputStream bos = null;
  40. try {
  41. bis = new BufferedInputStream(is);
  42. bos = new BufferedOutputStream(out);
  43. byte[] buff = new byte[2048];
  44. int bytesRead;
  45. while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
  46. bos.write(buff, 0, bytesRead);
  47. }
  48. } catch (final IOException e) {
  49. throw e;
  50. } finally {
  51. if (bis != null) bis.close();
  52. if (bos != null) bos.close();
  53. }
  54. }
  55. private static List<Map<String, Object>> createExcelRecord(List<?> projects, String[] keys) {
  56. List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
  57. Map<String, Object> map = new HashMap<String, Object>();
  58. map.put("sheetName", "sheet");
  59. listmap.add(map);
  60. Object project = null;
  61. for (int j = 0; j < projects.size(); j++) {
  62. project = projects.get(j);
  63. Map<String, Object> mapValue = new HashMap<String, Object>();
  64. for (int i = 0; i < keys.length; i++) {
  65. mapValue.put(keys[i], getFieldValueByName(keys[i], project));
  66. }
  67. listmap.add(mapValue);
  68. }
  69. return listmap;
  70. }
  71. /**
  72. * 利用反射 根据属性名获取属性值
  73. */
  74. private static Object getFieldValueByName(String fieldName, Object o) {
  75. try {
  76. String firstLetter = fieldName.substring(0, 1).toUpperCase();
  77. String getter = "get" + firstLetter + fieldName.substring(1);
  78. Method method = o.getClass().getMethod(getter);
  79. Object value = method.invoke(o);
  80. return value;
  81. } catch (Exception e) {
  82. e.printStackTrace();
  83. return null;
  84. }
  85. }
  86. /**
  87. * 创建excel文档对象
  88. *
  89. * @param keys list中map的key数组集合
  90. * @param columnNames excel的列名
  91. */
  92. private static Workbook createWorkBook(List<Map<String, Object>> list, String[] keys, String[] columnNames) {
  93. // 创建excel工作簿
  94. Workbook wb = new XSSFWorkbook();
  95. // 创建第一个sheet(页),并命名
  96. Sheet sheet = wb.createSheet(list.get(0).get("sheetName").toString());
  97. // 手动设置列宽。第一个参数表示要为第几列设;,第二个参数表示列的宽度,n为列高的像素数。
  98. for (int i = 0; i < keys.length; i++) {
  99. sheet.setColumnWidth((short) i, (short) (35.7 * 150));
  100. }
  101. // 创建第一行
  102. Row row = sheet.createRow((short) 0);
  103. // 创建两种单元格格式
  104. CellStyle cs = wb.createCellStyle();
  105. CellStyle cs2 = wb.createCellStyle();
  106. // 创建两种字体
  107. Font f = wb.createFont();
  108. Font f2 = wb.createFont();
  109. // 创建第一种字体样式(用于列名)
  110. f.setFontHeightInPoints((short) 10);
  111. f.setColor(IndexedColors.BLACK.getIndex());
  112. f.setBold(true);
  113. // 创建第二种字体样式(用于值)
  114. f2.setFontHeightInPoints((short) 10);
  115. f2.setColor(IndexedColors.BLACK.getIndex());
  116. // 设置第一种单元格的样式(用于列名)
  117. cs.setFont(f);
  118. cs.setBorderLeft(BorderStyle.THIN);
  119. cs.setBorderRight(BorderStyle.THIN);
  120. cs.setBorderTop(BorderStyle.THIN);
  121. cs.setBorderBottom(BorderStyle.THIN);
  122. cs.setAlignment(HorizontalAlignment.CENTER);
  123. // 设置第二种单元格的样式(用于值)
  124. cs2.setFont(f2);
  125. cs2.setBorderLeft(BorderStyle.THIN);
  126. cs2.setBorderRight(BorderStyle.THIN);
  127. cs2.setBorderTop(BorderStyle.THIN);
  128. cs2.setBorderBottom(BorderStyle.THIN);
  129. cs2.setAlignment(HorizontalAlignment.CENTER);
  130. //设置列名
  131. for (int i = 0; i < columnNames.length; i++) {
  132. Cell cell = row.createCell(i);
  133. cell.setCellValue(columnNames[i]);
  134. cell.setCellStyle(cs);
  135. }
  136. //设置每行每列的值
  137. for (short i = 1; i < list.size(); i++) {
  138. // Row 行,Cell 方格 , Row 和 Cell 都是从0开始计数的
  139. // 创建一行,在页sheet上
  140. Row row1 = sheet.createRow(i);
  141. // 在row行上创建一个方格
  142. for (short j = 0; j < keys.length; j++) {
  143. Cell cell = row1.createCell(j);
  144. cell.setCellValue(list.get(i).get(keys[j]) == null ? " " : list.get(i).get(keys[j]).toString());
  145. cell.setCellStyle(cs2);
  146. }
  147. }
  148. return wb;
  149. }
  150. }