当前位置:   article > 正文

POI 3.17 导出Excel,基础代码_poi3.17使用commons-lang3

poi3.17使用commons-lang3

工作中经常要用到excel的导出,所以参考其他人的demo写了一个导出excel的基础代码。如果以后再需要用的时候,直接拿来修改下就能直接使用。

参考博文地址:https://blog.csdn.net/phil_jing/article/details/78307819

以下是maven依赖

  1. <dependency>
  2. <groupId>org.apache.poi</groupId>
  3. <artifactId>poi</artifactId>
  4. <version>3.17</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.apache.poi</groupId>
  8. <artifactId>poi-ooxml</artifactId>
  9. <version>3.17</version>
  10. </dependency>

工具包

  1. <dependency>
  2. <groupId>org.apache.commons</groupId>
  3. <artifactId>commons-lang3</artifactId>
  4. <version>3.9</version>
  5. </dependency>

以下是导出代码实现

  1. package com.example.demo.utils;
  2. import org.apache.commons.lang3.StringUtils;
  3. import org.apache.poi.ss.util.CellRangeAddress;
  4. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  5. import org.apache.commons.lang3.time.FastDateFormat;
  6. import java.util.Collection;
  7. import java.util.Date;
  8. import java.util.Iterator;
  9. import java.util.Map;
  10. import java.util.regex.Matcher;
  11. import java.util.regex.Pattern;
  12. import org.apache.poi.ss.usermodel.*;
  13. import org.apache.poi.ss.usermodel.Cell;
  14. import org.apache.poi.ss.usermodel.CellStyle;
  15. import org.apache.poi.ss.usermodel.FillPatternType;
  16. import org.apache.poi.ss.usermodel.Font;
  17. import org.apache.poi.ss.usermodel.HorizontalAlignment;
  18. import org.apache.poi.ss.usermodel.IndexedColors;
  19. import org.apache.poi.ss.usermodel.Row;
  20. import org.apache.poi.ss.usermodel.Sheet;
  21. import org.apache.poi.ss.usermodel.VerticalAlignment;
  22. import org.apache.poi.ss.usermodel.Workbook;
  23. public class ExportExcel {
  24. /**
  25. * excel导出
  26. * @param sheetName sheet名称
  27. * @param title 标题
  28. * @param headers 表头
  29. * @param columns 字段名称
  30. * @param dataset 数据集合
  31. * @param pattern 日期格式
  32. * @return Workbook
  33. */
  34. public static Workbook exportExcel(String sheetName, String title, String[] headers, String[] columns,
  35. Collection<Map<String, Object>> dataset, String pattern){
  36. // 创建excel工作簿
  37. Workbook workbook = new XSSFWorkbook();
  38. // 创建第一个sheet(页),并命名
  39. Sheet sheet = workbook.createSheet(sheetName);
  40. // -----------------表格标题行样式-----------------
  41. CellStyle titleStyle = workbook.createCellStyle();
  42. // 设置这些样式
  43. titleStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); // 填充颜色
  44. titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); // 填充样式
  45. titleStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
  46. titleStyle.setVerticalAlignment(VerticalAlignment.CENTER); //垂直居中
  47. titleStyle.setBorderBottom(BorderStyle.THIN);
  48. titleStyle.setBorderLeft(BorderStyle.THIN);
  49. titleStyle.setBorderRight(BorderStyle.THIN);
  50. titleStyle.setBorderTop(BorderStyle.THIN);
  51. // 生成一个字体
  52. Font font = workbook.createFont();
  53. font.setColor(IndexedColors.WHITE.getIndex());
  54. font.setFontHeightInPoints((short) 12);
  55. font.setBold(true);
  56. // font.setBoldweight((short)700));
  57. // 把字体应用到当前的样式
  58. titleStyle.setFont(font);
  59. // ----------------样式2 内容的背景----------------
  60. CellStyle style2 = workbook.createCellStyle();
  61. style2.setFillForegroundColor(IndexedColors.WHITE.getIndex());
  62. style2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
  63. style2.setBorderBottom(BorderStyle.THIN);
  64. style2.setBorderLeft(BorderStyle.THIN);
  65. style2.setBorderRight(BorderStyle.THIN);
  66. style2.setBorderTop(BorderStyle.THIN);
  67. style2.setAlignment(HorizontalAlignment.CENTER);
  68. style2.setVerticalAlignment(VerticalAlignment.CENTER);
  69. // 生成另一个字体
  70. Font font2 = workbook.createFont();
  71. font.setBold(true);
  72. // font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
  73. // 把字体应用到当前的样式
  74. style2.setFont(font2);
  75. int rowCount = 0; // 起始行号
  76. Row row;
  77. // ------------设置首行标题标题--------------
  78. if (StringUtils.isNotEmpty(title)){
  79. // 如果有标题
  80. row = sheet.createRow(rowCount);
  81. Cell cell = row.createCell(rowCount);
  82. cell.setCellValue(title);
  83. cell.setCellStyle(titleStyle);
  84. //合并单元格
  85. CellRangeAddress region = new CellRangeAddress(rowCount, rowCount, 0, headers.length-1);
  86. sheet.addMergedRegion(region);
  87. rowCount++;
  88. }
  89. // ----------------表头------------------
  90. row = sheet.createRow(rowCount);
  91. //
  92. for (int i = 0; i < headers.length; i++) {
  93. Cell cell = row.createCell(i);
  94. cell.setCellStyle(titleStyle);
  95. // 富文本字符串:用于同一单元格内容展示不用样式
  96. // RichTextString text = new XSSFRichTextString(headers[i]);
  97. cell.setCellValue(headers[i]);
  98. }
  99. rowCount++;
  100. // --------------单元格数据----------------
  101. if(StringUtils.isEmpty(pattern)) {
  102. pattern = "yyyy/MM/dd";
  103. }
  104. FastDateFormat instance = FastDateFormat.getInstance(pattern);
  105. // 遍历集合数据,产生数据行
  106. Iterator<Map<String, Object>> it = dataset.iterator(); // 多个Map集合
  107. int count = 0;
  108. while (it.hasNext()) {
  109. row = sheet.createRow(rowCount);
  110. Map<String, Object> map = it.next();
  111. count = headers.length < columns.length ? headers.length : columns.length;
  112. for (int i = 0; i < count; i++) {
  113. Cell cell = row.createCell(i);
  114. cell.setCellStyle(style2);
  115. try {
  116. Object value = map.get(columns[i]);
  117. // 判断值的类型后进行强制类型转换
  118. String textValue = null;
  119. if (value instanceof Date) {
  120. Date date = (Date) value;
  121. textValue = instance.format(date);
  122. }else {
  123. // 其它数据类型都当作字符串简单处理
  124. if (value != null) {
  125. textValue = value.toString();
  126. } else {
  127. textValue = "";
  128. }
  129. }
  130. // 利用正则表达式判断textValue是否全部由数字组成
  131. if (textValue != null) {
  132. Pattern p = Pattern.compile("^//d+(//.//d+)?$");
  133. Matcher matcher = p.matcher(textValue);
  134. if (matcher.matches()) {
  135. // 是数字当作double处理
  136. cell.setCellValue(Double.parseDouble(textValue));
  137. } else {
  138. cell.setCellValue(textValue);
  139. cell.setCellStyle(style2);
  140. }
  141. }
  142. } catch (SecurityException e) {
  143. e.printStackTrace();
  144. }
  145. }
  146. rowCount++;
  147. }
  148. return workbook;
  149. }
  150. }

控制层调用

  1. package com.example.demo.controller;
  2. import com.example.demo.model.Bean;
  3. import com.example.demo.utils.ExportExcel;
  4. import org.apache.poi.ss.usermodel.Workbook;
  5. import org.springframework.util.StringUtils;
  6. import org.springframework.web.bind.annotation.*;
  7. import javax.servlet.http.HttpServletResponse;
  8. import java.time.LocalTime;
  9. import java.util.*;
  10. @RestController
  11. public class TestController {
  12. private static String EXPORT_XLSX_FILE_SUFFIX = ".xlsx";
  13. private static String EXPORT_XLS_FILE_SUFFIX = ".xls";
  14. /**
  15. * 导出
  16. */
  17. @RequestMapping(value = "/export")
  18. public void getExcel1(@RequestParam Map<String, Object> map, HttpServletResponse response) throws Exception {
  19. LocalTime localTime1 = LocalTime.now();
  20. System.out.println("开始时间:" + localTime1);
  21. //查询条件
  22. System.out.println((String) map.get("name"));
  23. //
  24. List<Bean> beanList = new ArrayList<>();
  25. for (int i = 0; i<10000; i++){
  26. Bean bean1 = new Bean();
  27. bean1.setAttribute("属性" + i);
  28. bean1.setName("字段" + i);
  29. bean1.setLength(i);
  30. bean1.setType("类型" + i);
  31. bean1.setNote("注释" + i);
  32. beanList.add(bean1);
  33. }
  34. List<Map<String,Object>> list = new ArrayList<>();
  35. for (Bean bean : beanList) {
  36. Map<String,Object> hashMap = new HashMap<>();
  37. //
  38. hashMap.put("attribute",bean.getAttribute());
  39. hashMap.put("name",bean.getName());
  40. hashMap.put("length",bean.getLength());
  41. hashMap.put("type",bean.getType());
  42. hashMap.put("note",bean.getNote());
  43. //
  44. list.add(hashMap);
  45. }
  46. String sheetName = "sheet1";
  47. String title1 = "标题"; // 标题
  48. String[] title2 = {"属性", "字段", "长度","类型","注释"}; // 表头
  49. String[] columns = {"attribute", "name", "length","type","note"}; // 字段
  50. String pattern = "yyyy/MM/dd"; // 日期格式
  51. //
  52. String excelType;
  53. if(StringUtils.isEmpty(map.get("excel_type"))) {
  54. excelType = EXPORT_XLSX_FILE_SUFFIX;
  55. } else {
  56. excelType = (String) map.get("excel_type");
  57. }
  58. Workbook workbook = ExportExcel.exportExcel(sheetName,title1,title2,columns,list,pattern);
  59. response.setHeader("Content-type", "application/vnd.ms-excel");
  60. response.setCharacterEncoding("UTF-8");
  61. response.setHeader("Content-Disposition", "attachment;filename=" + System.currentTimeMillis() + excelType);
  62. workbook.write(response.getOutputStream());
  63. workbook.close();
  64. //
  65. LocalTime localTime2 = LocalTime.now();
  66. System.out.println("结束时间:" + localTime2);
  67. }
  68. }

项目启动后,在浏览器地址栏输入:localhost:8080/export?excel_type=.xls&name=小明

导出1w条数据所用时间大概为3-4秒

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/170221
推荐阅读
相关标签
  

闽ICP备14008679号