ExportExcel.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. package platform.common.util;
  2. import com.google.common.collect.Lists;
  3. import org.apache.commons.lang3.StringUtils;
  4. import org.apache.poi.ss.usermodel.*;
  5. import org.apache.poi.ss.util.CellRangeAddress;
  6. import org.apache.poi.xssf.streaming.SXSSFSheet;
  7. import org.apache.poi.xssf.streaming.SXSSFWorkbook;
  8. import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
  9. import org.apache.poi.xssf.usermodel.XSSFRichTextString;
  10. import org.slf4j.Logger;
  11. import org.slf4j.LoggerFactory;
  12. import platform.common.annotation.ExcelField;
  13. import javax.servlet.http.HttpServletResponse;
  14. import java.io.FileNotFoundException;
  15. import java.io.FileOutputStream;
  16. import java.io.IOException;
  17. import java.io.OutputStream;
  18. import java.lang.reflect.Field;
  19. import java.lang.reflect.Method;
  20. import java.net.URLEncoder;
  21. import java.util.*;
  22. public class ExportExcel {
  23. private static Logger log = LoggerFactory.getLogger(ExportExcel.class);
  24. /**
  25. * 工作薄对象
  26. */
  27. private SXSSFWorkbook wb;
  28. /**
  29. * 工作表对象
  30. */
  31. private Sheet sheet;
  32. /**
  33. * 样式列表
  34. */
  35. private Map<String, CellStyle> styles;
  36. /**
  37. * 当前行号
  38. */
  39. private int rownum;
  40. /**
  41. * 注解列表(Object[]{ ExcelField, Field/Method })
  42. */
  43. List<Object[]> annotationList = Lists.newArrayList();
  44. /**
  45. * 构造函数
  46. *
  47. * @param title 表格标题,传“空值”,表示无标题
  48. * @param cls 实体对象,通过annotation.ExportField获取标题
  49. */
  50. public ExportExcel(String title, Class<?> cls) {
  51. this(title, cls, 1);
  52. }
  53. /**
  54. * 构造函数
  55. *
  56. * @param title 表格标题,传“空值”,表示无标题
  57. * @param cls 实体对象,通过annotation.ExportField获取标题
  58. * @param type 导出类型(1:导出数据;2:导出模板)
  59. * @param groups 导入分组
  60. */
  61. public ExportExcel(String title, Class<?> cls, int type, int... groups) {
  62. // Get annotation field
  63. Field[] fs = cls.getDeclaredFields();
  64. for (Field f : fs) {
  65. ExcelField ef = f.getAnnotation(ExcelField.class);
  66. if (ef != null && (ef.type() == 0 || ef.type() == type)) {
  67. if (groups != null && groups.length > 0) {
  68. boolean inGroup = false;
  69. for (int g : groups) {
  70. if (inGroup) {
  71. break;
  72. }
  73. for (int efg : ef.groups()) {
  74. if (g == efg) {
  75. inGroup = true;
  76. annotationList.add(new Object[]{ef, f});
  77. break;
  78. }
  79. }
  80. }
  81. } else {
  82. annotationList.add(new Object[]{ef, f});
  83. }
  84. }
  85. }
  86. // Get annotation method
  87. Method[] ms = cls.getDeclaredMethods();
  88. for (Method m : ms) {
  89. ExcelField ef = m.getAnnotation(ExcelField.class);
  90. if (ef != null && (ef.type() == 0 || ef.type() == type)) {
  91. if (groups != null && groups.length > 0) {
  92. boolean inGroup = false;
  93. for (int g : groups) {
  94. if (inGroup) {
  95. break;
  96. }
  97. for (int efg : ef.groups()) {
  98. if (g == efg) {
  99. inGroup = true;
  100. annotationList.add(new Object[]{ef, m});
  101. break;
  102. }
  103. }
  104. }
  105. } else {
  106. annotationList.add(new Object[]{ef, m});
  107. }
  108. }
  109. }
  110. // Field sorting
  111. Collections.sort(annotationList, new Comparator<Object[]>() {
  112. public int compare(Object[] o1, Object[] o2) {
  113. return new Integer(((ExcelField) o1[0]).sort()).compareTo(
  114. new Integer(((ExcelField) o2[0]).sort()));
  115. }
  116. ;
  117. });
  118. // Initialize
  119. List<String> headerList = Lists.newArrayList();
  120. for (Object[] os : annotationList) {
  121. String t = ((ExcelField) os[0]).title();
  122. // 如果是导出,则去掉注释
  123. if (type == 1) {
  124. String[] ss = StringUtils.split(t, "**", 2);
  125. if (ss.length == 2) {
  126. t = ss[0];
  127. }
  128. }
  129. headerList.add(t);
  130. }
  131. initialize(title, headerList);
  132. }
  133. /**
  134. * 构造函数
  135. *
  136. * @param title 表格标题,传“空值”,表示无标题
  137. * @param headerList 表头列表
  138. */
  139. public ExportExcel(String title, List<String> headerList) {
  140. initialize(title, headerList);
  141. }
  142. /**
  143. * 添加数据(通过annotation.ExportField添加数据)
  144. *
  145. * @return list 数据列表
  146. */
  147. public <E> ExportExcel setDataList(List<E> list) {
  148. for (E e : list) {
  149. int colunm = 0;
  150. Row row = this.addRow();
  151. StringBuilder sb = new StringBuilder();
  152. for (Object[] os : annotationList) {
  153. ExcelField ef = (ExcelField) os[0];
  154. Object val = null;
  155. // Get entity value
  156. try {
  157. if (StringUtils.isNotBlank(ef.value())) {
  158. val = Reflections.invokeGetter(e, ef.value());
  159. } else {
  160. if (os[1] instanceof Field) {
  161. val = Reflections.invokeGetter(e, ((Field) os[1]).getName());
  162. } else if (os[1] instanceof Method) {
  163. val = Reflections.invokeMethod(e, ((Method) os[1]).getName(), new Class[]{}, new Object[]{});
  164. }
  165. }
  166. } catch (Exception ex) {
  167. // Failure to ignore
  168. log.info(ex.toString());
  169. val = "";
  170. }
  171. this.addCell(row, colunm++, val, ef.align(), ef.fieldType());
  172. sb.append(val + ", ");
  173. }
  174. log.debug("Write success: [" + row.getRowNum() + "] " + sb.toString());
  175. }
  176. return this;
  177. }
  178. /**
  179. * 初始化函数
  180. *
  181. * @param title 表格标题,传“空值”,表示无标题
  182. * @param headerList 表头列表
  183. */
  184. private void initialize(String title, List<String> headerList) {
  185. this.wb = new SXSSFWorkbook(500);
  186. this.sheet = wb.createSheet("Export");
  187. this.styles = createStyles(wb);
  188. // Create title
  189. if (StringUtils.isNotBlank(title)) {
  190. Row titleRow = sheet.createRow(rownum++);
  191. titleRow.setHeightInPoints(30);
  192. Cell titleCell = titleRow.createCell(0);
  193. titleCell.setCellStyle(styles.get("title"));
  194. titleCell.setCellValue(title);
  195. sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(),
  196. titleRow.getRowNum(), titleRow.getRowNum(), headerList.size() - 1));
  197. }
  198. // Create header
  199. if (headerList == null) {
  200. throw new RuntimeException("headerList not null!");
  201. }
  202. Row headerRow = sheet.createRow(rownum++);
  203. headerRow.setHeightInPoints(16);
  204. for (int i = 0; i < headerList.size(); i++) {
  205. Cell cell = headerRow.createCell(i);
  206. cell.setCellStyle(styles.get("header"));
  207. String[] ss = StringUtils.split(headerList.get(i), "**", 2);
  208. if (ss.length == 2) {
  209. cell.setCellValue(ss[0]);
  210. Comment comment = this.sheet.createDrawingPatriarch().createCellComment(
  211. new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6));
  212. comment.setString(new XSSFRichTextString(ss[1]));
  213. cell.setCellComment(comment);
  214. } else {
  215. cell.setCellValue(headerList.get(i));
  216. }
  217. // sheet.autoSizeColumn(i);
  218. }
  219. for (int i = 0; i < headerList.size(); i++) {
  220. int colWidth = sheet.getColumnWidth(i) * 2;
  221. sheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth);
  222. }
  223. log.debug("Initialize success.");
  224. }
  225. /**
  226. * 创建表格样式
  227. *
  228. * @param wb 工作薄对象
  229. * @return 样式列表
  230. */
  231. private Map<String, CellStyle> createStyles(Workbook wb) {
  232. Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
  233. CellStyle style = wb.createCellStyle();
  234. style.setAlignment(HorizontalAlignment.CENTER);
  235. style.setVerticalAlignment(VerticalAlignment.CENTER);
  236. Font titleFont = wb.createFont();
  237. titleFont.setFontName("Arial");
  238. titleFont.setFontHeightInPoints((short) 16);
  239. titleFont.setBold(true);
  240. style.setFont(titleFont);
  241. styles.put("title", style);
  242. style = wb.createCellStyle();
  243. style.setVerticalAlignment(VerticalAlignment.CENTER);
  244. style.setBorderRight(BorderStyle.THIN);
  245. style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  246. style.setBorderLeft(BorderStyle.THIN);
  247. style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  248. style.setBorderTop(BorderStyle.THIN);
  249. style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  250. style.setBorderBottom(BorderStyle.THIN);
  251. style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
  252. Font dataFont = wb.createFont();
  253. dataFont.setFontName("Arial");
  254. dataFont.setFontHeightInPoints((short) 10);
  255. style.setFont(dataFont);
  256. styles.put("data", style);
  257. style = wb.createCellStyle();
  258. style.cloneStyleFrom(styles.get("data"));
  259. style.setAlignment(HorizontalAlignment.LEFT);
  260. styles.put("data1", style);
  261. style = wb.createCellStyle();
  262. style.cloneStyleFrom(styles.get("data"));
  263. style.setAlignment(HorizontalAlignment.CENTER);
  264. styles.put("data2", style);
  265. style = wb.createCellStyle();
  266. style.cloneStyleFrom(styles.get("data"));
  267. style.setAlignment(HorizontalAlignment.RIGHT);
  268. styles.put("data3", style);
  269. style = wb.createCellStyle();
  270. style.cloneStyleFrom(styles.get("data"));
  271. // style.setWrapText(true);
  272. style.setAlignment(HorizontalAlignment.CENTER);
  273. style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
  274. style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  275. Font headerFont = wb.createFont();
  276. headerFont.setFontName("Arial");
  277. headerFont.setFontHeightInPoints((short) 10);
  278. headerFont.setBold(true);
  279. headerFont.setColor(IndexedColors.WHITE.getIndex());
  280. style.setFont(headerFont);
  281. styles.put("header", style);
  282. return styles;
  283. }
  284. /**
  285. * 添加一行
  286. *
  287. * @return 行对象
  288. */
  289. public Row addRow() {
  290. return sheet.createRow(rownum++);
  291. }
  292. /**
  293. * 添加一个单元格
  294. *
  295. * @param row 添加的行
  296. * @param column 添加列号
  297. * @param val 添加值
  298. * @return 单元格对象
  299. */
  300. public Cell addCell(Row row, int column, Object val) {
  301. return this.addCell(row, column, val, 0, Class.class);
  302. }
  303. /**
  304. * 添加一个单元格
  305. *
  306. * @param row 添加的行
  307. * @param column 添加列号
  308. * @param val 添加值
  309. * @param align 对齐方式(1:靠左;2:居中;3:靠右)
  310. * @return 单元格对象
  311. */
  312. public Cell addCell(Row row, int column, Object val, int align, Class<?> fieldType) {
  313. Cell cell = row.createCell(column);
  314. String cellFormatString = "@";
  315. try {
  316. if (val == null) {
  317. cell.setCellValue("");
  318. } else if (fieldType != Class.class) {
  319. cell.setCellValue((String) fieldType.getMethod("setValue", Object.class).invoke(null, val));
  320. } else {
  321. if (val instanceof String) {
  322. cell.setCellValue((String) val);
  323. } else if (val instanceof Integer) {
  324. cell.setCellValue((Integer) val);
  325. cellFormatString = "0";
  326. } else if (val instanceof Long) {
  327. cell.setCellValue((Long) val);
  328. cellFormatString = "0";
  329. } else if (val instanceof Double) {
  330. cell.setCellValue((Double) val);
  331. cellFormatString = "0.00";
  332. } else if (val instanceof Float) {
  333. cell.setCellValue((Float) val);
  334. cellFormatString = "0.00";
  335. } else if (val instanceof Date) {
  336. cell.setCellValue((Date) val);
  337. cellFormatString = "yyyy-MM-dd HH:mm";
  338. } else {
  339. cell.setCellValue((String) Class.forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(),
  340. "fieldtype." + val.getClass().getSimpleName() + "Type")).getMethod("setValue", Object.class).invoke(null, val));
  341. }
  342. }
  343. // if (val != null){
  344. CellStyle style = styles.get("data_column_" + column);
  345. if (style == null) {
  346. style = wb.createCellStyle();
  347. style.cloneStyleFrom(styles.get("data" + (align >= 1 && align <= 3 ? align : "")));
  348. style.setDataFormat(wb.createDataFormat().getFormat(cellFormatString));
  349. styles.put("data_column_" + column, style);
  350. }
  351. cell.setCellStyle(style);
  352. // }
  353. } catch (Exception ex) {
  354. log.info("Set cell value [" + row.getRowNum() + "," + column + "] error: " + ex.toString());
  355. cell.setCellValue(val.toString());
  356. }
  357. return cell;
  358. }
  359. /**
  360. * 输出数据流
  361. *
  362. * @param os 输出数据流
  363. */
  364. public ExportExcel write(OutputStream os) throws IOException {
  365. wb.write(os);
  366. return this;
  367. }
  368. /**
  369. * 输出到客户端
  370. *
  371. * @param fileName 输出文件名
  372. */
  373. public ExportExcel write(HttpServletResponse response, String fileName) throws IOException {
  374. response.reset();
  375. response.setContentType("application/octet-stream; charset=utf-8");
  376. response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
  377. write(response.getOutputStream());
  378. return this;
  379. }
  380. /**
  381. * 输出到文件
  382. *
  383. * @param name 输出文件名
  384. */
  385. public ExportExcel writeFile(String name) throws FileNotFoundException, IOException {
  386. FileOutputStream os = new FileOutputStream(name);
  387. this.write(os);
  388. return this;
  389. }
  390. /**
  391. * 清理临时文件
  392. */
  393. public ExportExcel dispose() {
  394. wb.dispose();
  395. return this;
  396. }
  397. /**
  398. * 导出测试
  399. */
  400. public static void main(String[] args) throws Throwable {
  401. List<String> headerList = Lists.newArrayList();
  402. for (int i = 1; i <= 10; i++) {
  403. headerList.add("表头" + i);
  404. }
  405. List<String> dataRowList = Lists.newArrayList();
  406. for (int i = 1; i <= headerList.size(); i++) {
  407. dataRowList.add("数据" + i);
  408. }
  409. List<List<String>> dataList = Lists.newArrayList();
  410. for (int i = 1; i <= 1000000; i++) {
  411. dataList.add(dataRowList);
  412. }
  413. ExportExcel ee = new ExportExcel("表格标题", headerList);
  414. for (int i = 0; i < dataList.size(); i++) {
  415. Row row = ee.addRow();
  416. for (int j = 0; j < dataList.get(i).size(); j++) {
  417. ee.addCell(row, j, dataList.get(i).get(j));
  418. }
  419. }
  420. ee.writeFile("target/export.xlsx");
  421. ee.dispose();
  422. log.debug("Export success.");
  423. }
  424. }