当前位置:   article > 正文

springboot导出excel(easyexcel和poi 列下拉及表格锁定)_java easypoi 锁定列

java easypoi 锁定列

最近做的项目导入的数据量比较大,直接用poi或者easypoi会可能会出现OOM的情况,综合考虑下用easyexcel

pom引入所需包

  1. <!-- https://mvnrepository.com/artifact/com.alibaba/easyexcel -->
  2. <dependency>
  3. <groupId>com.alibaba</groupId>
  4. <artifactId>easyexcel</artifactId>
  5. <version>1.1.2-beta5</version>
  6. </dependency>

excelUtil.java

  1. import com.alibaba.excel.EasyExcelFactory;
  2. import com.alibaba.excel.ExcelReader;
  3. import com.alibaba.excel.ExcelWriter;
  4. import com.alibaba.excel.metadata.BaseRowModel;
  5. import com.alibaba.excel.metadata.Sheet;
  6. import com.alibaba.excel.support.ExcelTypeEnum;
  7. import com.alibaba.excel.util.CollectionUtils;
  8. import com.cmbchina.ccd.oa.socialsecurity.model.bo.ExcelListener;
  9. import org.springframework.stereotype.Component;
  10. import org.springframework.web.multipart.MultipartFile;
  11. import javax.servlet.ServletOutputStream;
  12. import javax.servlet.http.HttpServletResponse;
  13. import java.io.BufferedInputStream;
  14. import java.io.FileNotFoundException;
  15. import java.io.FileOutputStream;
  16. import java.io.IOException;
  17. import java.io.InputStream;
  18. import java.io.OutputStream;
  19. import java.util.ArrayList;
  20. import java.util.Collections;
  21. import java.util.HashMap;
  22. import java.util.List;
  23. import java.util.Map;
  24. /**
  25. * @description: excel工具类
  26. * @author: kongwc
  27. * @create: 2019-09-23
  28. */
  29. @Component
  30. public class ExcelUtil {
  31. private static Sheet initSheet;
  32. static {
  33. initSheet = new Sheet(1, 0);
  34. initSheet.setSheetName("sheet");
  35. //设置自适应宽度
  36. initSheet.setAutoWidth(Boolean.TRUE);
  37. }
  38. /**
  39. * 读取少于1000行数据
  40. * 数据量少时,同步读取
  41. *
  42. * @param file 读取的文件
  43. * @return
  44. */
  45. public List<Object> readLessThan1000Row(MultipartFile file) throws IOException {
  46. return readLessThan1000RowBySheet(file, null);
  47. }
  48. /**
  49. * 读小于1000行数据
  50. * filePath 文件绝对路径
  51. * initSheet :
  52. * sheetNo: sheet页码,默认为1
  53. * headLineMun: 从第几行开始读取数据,默认为0, 表示从第一行开始读取
  54. * clazz: 返回数据List<Object> 中Object的类名
  55. */
  56. public List<Object> readLessThan1000RowBySheet(MultipartFile file, Sheet sheet) throws IOException {
  57. if (file == null) {
  58. //log.info("导入文件为空", file);
  59. return null;
  60. }
  61. sheet = sheet != null ? sheet : initSheet;
  62. InputStream fileStream = null;
  63. try {
  64. fileStream = file.getInputStream();
  65. return EasyExcelFactory.read(fileStream, sheet);
  66. } catch (FileNotFoundException e) {
  67. //log.info("文件有误, 文件:{}", file);
  68. } finally {
  69. try {
  70. if (fileStream != null) {
  71. fileStream.close();
  72. }
  73. } catch (IOException e) {
  74. //log.info("excel文件读取失败, 失败原因:{}", e);
  75. }
  76. }
  77. return null;
  78. }
  79. /**
  80. * 生成excle
  81. *
  82. * @param filePath 绝对路径, 如:/home/Downloads/aaa.xlsx
  83. * @param data 数据源
  84. * @param head 表头
  85. */
  86. public static void writeBySimple(String filePath, List<List<Object>> data, List<String> head) {
  87. writeSimpleBySheet(filePath, data, head, null);
  88. }
  89. /**
  90. * 生成excle
  91. *
  92. * @param filePath 绝对路径
  93. * @param data 数据源
  94. * @param sheet excle页面样式
  95. * @param head 表头
  96. */
  97. public static void writeSimpleBySheet(String filePath, List<List<Object>> data, List<String> head, Sheet sheet) {
  98. sheet = (sheet != null) ? sheet : initSheet;
  99. if (head != null) {
  100. List<List<String>> list = new ArrayList<>();
  101. head.forEach(h -> list.add(Collections.singletonList(h)));
  102. sheet.setHead(list);
  103. }
  104. OutputStream outputStream = null;
  105. ExcelWriter writer = null;
  106. try {
  107. outputStream = new FileOutputStream(filePath);
  108. writer = EasyExcelFactory.getWriter(outputStream);
  109. writer.write1(data, sheet);
  110. } catch (FileNotFoundException e) {
  111. //log.error("找不到文件或文件路径错误, 文件:{}", filePath);
  112. } finally {
  113. try {
  114. if (writer != null) {
  115. writer.finish();
  116. }
  117. if (outputStream != null) {
  118. outputStream.close();
  119. }
  120. } catch (IOException e) {
  121. //log.error("excel文件导出失败");
  122. }
  123. }
  124. }
  125. /**
  126. * @Description 导出excel 支持一张表导出多个sheet
  127. * @Param OutputStream 输出流
  128. * Map<String, List> sheetName和每个sheet的数据
  129. * ExcelTypeEnum 要导出的excel的类型 有ExcelTypeEnum.xls 和有ExcelTypeEnum.xlsx
  130. */
  131. public void createExcel(HttpServletResponse response, Map<String, List<? extends BaseRowModel>> sheetNameAndDateList, ExcelTypeEnum type, String fileName) {
  132. // if (checkParam(SheetNameAndDateList, type)) return;
  133. try {
  134. response.setContentType("multipart/form-data");
  135. response.setCharacterEncoding("utf-8");
  136. //解决导出文件名中文乱码
  137. fileName = new String(fileName.getBytes(), "iso8859-1") + DateUtil.todayStr();
  138. response.setHeader("Content-disposition", "attachment;filename=" + fileName + type.getValue());
  139. ServletOutputStream out = response.getOutputStream();
  140. ExcelWriter writer = new ExcelWriter(out, type, true);
  141. setSheet(sheetNameAndDateList, writer);
  142. writer.finish();
  143. out.flush();
  144. } catch (IOException e) {
  145. e.printStackTrace();
  146. }
  147. }
  148. /**
  149. * @Description //setSheet数据
  150. */
  151. private void setSheet(Map<String, List<? extends BaseRowModel>> SheetNameAndDateList, ExcelWriter writer) {
  152. int sheetNum = 1;
  153. for (Map.Entry<String, List<? extends BaseRowModel>> stringListEntry : SheetNameAndDateList.entrySet()) {
  154. Sheet sheet = new Sheet(sheetNum, 0, stringListEntry.getValue().get(0).getClass());
  155. sheet.setSheetName(stringListEntry.getKey());
  156. writer.write(stringListEntry.getValue(), sheet);
  157. sheetNum++;
  158. }
  159. }
  160. /**
  161. * @Description 校验参数
  162. */
  163. private static boolean checkParam(Map<String, List<? extends BaseRowModel>> SheetNameAndDateList, ExcelTypeEnum type) {
  164. if (CollectionUtils.isEmpty(SheetNameAndDateList)) {
  165. //log.error("SheetNameAndDateList不能为空");
  166. return true;
  167. } else if (type == null) {
  168. //log.error("导出的excel类型不能为空");
  169. return true;
  170. }
  171. return false;
  172. }
  173. /**
  174. * 读取某个 sheet 的 Excel
  175. *
  176. * @param excel 文件
  177. * @param rowModel 实体类映射,继承 BaseRowModel 类
  178. * @return Excel 数据 list
  179. */
  180. public static List<Object> readExcel(MultipartFile excel, BaseRowModel rowModel) throws IOException {
  181. return readExcel(excel, rowModel, 1, 1);
  182. }
  183. /**
  184. * 读取某个 sheet 的 Excel
  185. *
  186. * @param excel 文件
  187. * @param rowModel 实体类映射,继承 BaseRowModel 类
  188. * @param sheetNo sheet 的序号 从1开始
  189. * @return Excel 数据 list
  190. */
  191. public Map<String, Object> readExcel(MultipartFile excel, BaseRowModel rowModel, int sheetNo) throws IOException {
  192. Map<String, Object> result = new HashMap<>();
  193. ExcelListener excelListener = new ExcelListener();
  194. ExcelReader reader = getReader(excel, excelListener);
  195. if (reader == null) {
  196. return null;
  197. }
  198. reader.read(new Sheet(sheetNo, 0, rowModel.getClass()));
  199. //校验表头
  200. Boolean flag = false;
  201. //维护实体类中 没有@ExcelProperty 放置在最后,会被映射出null表头
  202. String head = excelListener.getImportHeads().replace("null,", "");
  203. if (head.equals(excelListener.getModelHeads())) {
  204. flag = true;
  205. }
  206. result.put("flag", flag);
  207. result.put("datas", excelListener.getDatas());
  208. return result;
  209. }
  210. /**
  211. * 读取某个 sheet 的 Excel
  212. *
  213. * @param excel 文件
  214. * @param rowModel 实体类映射,继承 BaseRowModel 类
  215. * @param sheetNo sheet 的序号 从1开始
  216. * @param headLineNum 表头行数,默认为1
  217. * @return Excel 数据 list
  218. */
  219. public static List<Object> readExcel(MultipartFile excel, BaseRowModel rowModel, int sheetNo, int headLineNum) throws IOException {
  220. ExcelListener excelListener = new ExcelListener();
  221. ExcelReader reader = getReader(excel, excelListener);
  222. if (reader == null) {
  223. return null;
  224. }
  225. reader.read(new Sheet(sheetNo, headLineNum, rowModel.getClass()));
  226. return excelListener.getDatas();
  227. }
  228. /**
  229. * 读取指定sheetName的Excel(多个 sheet)
  230. *
  231. * @param excel 文件
  232. * @param rowModel 实体类映射,继承 BaseRowModel 类
  233. * @return Excel 数据 list
  234. * @throws IOException
  235. */
  236. public static List<Object> readExcel(MultipartFile excel, BaseRowModel rowModel, String sheetName) throws IOException {
  237. ExcelListener excelListener = new ExcelListener();
  238. ExcelReader reader = getReader(excel, excelListener);
  239. if (reader == null) {
  240. return null;
  241. }
  242. for (Sheet sheet : reader.getSheets()) {
  243. if (rowModel != null) {
  244. sheet.setClazz(rowModel.getClass());
  245. }
  246. //读取指定名称的sheet
  247. if (sheet.getSheetName().contains(sheetName)) {
  248. reader.read(sheet);
  249. break;
  250. }
  251. }
  252. return excelListener.getDatas();
  253. }
  254. /**
  255. * 返回 ExcelReader
  256. *
  257. * @param excel 需要解析的 Excel 文件
  258. * @param excelListener new ExcelListener()
  259. * @throws IOException
  260. */
  261. private static ExcelReader getReader(MultipartFile excel, ExcelListener excelListener) throws IOException {
  262. String filename = excel.getOriginalFilename();
  263. if (filename != null && (filename.toLowerCase().endsWith(".xls") || filename.toLowerCase().endsWith(".xlsx"))) {
  264. InputStream is = new BufferedInputStream(excel.getInputStream());
  265. return new ExcelReader(is, null, excelListener, false);
  266. } else {
  267. return null;
  268. }
  269. }
  270. }

但是easyexcel导出的功能还不丰富,比如带下拉选择的时候,还是需要原生的poi才行,所以决定导入数据量大的时候用easyexcel,导出时就用poi导出,由于easyexcel已引入poi,所以如果引入poi的时候要注意版本一致

pom文件

  1. <!--poi相关 -->
  2. <dependency>
  3. <groupId>org.apache.poi</groupId>
  4. <artifactId>poi-ooxml</artifactId>
  5. <version>3.17</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.apache.poi</groupId>
  9. <artifactId>poi</artifactId>
  10. <version>3.17</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.apache.poi</groupId>
  14. <artifactId>poi-scratchpad</artifactId>
  15. <version>3.17</version>
  16. </dependency>

PoiExcelUtil.java

  1. import com.alibaba.excel.util.StyleUtil;
  2. import com.cmbchina.ccd.oa.socialsecurity.model.bo.excel.ColumnName;
  3. import com.cmbchina.ccd.oa.socialsecurity.model.bo.excel.SelectData;
  4. import org.apache.commons.lang3.StringUtils;
  5. import org.apache.http.message.BasicNameValuePair;
  6. import org.apache.poi.hssf.util.HSSFColor;
  7. import org.apache.poi.ss.util.CellRangeAddressList;
  8. import org.apache.poi.xssf.usermodel.XSSFCell;
  9. import org.apache.poi.xssf.usermodel.XSSFCellStyle;
  10. import org.apache.poi.xssf.usermodel.XSSFDataValidation;
  11. import org.apache.poi.xssf.usermodel.XSSFDataValidationConstraint;
  12. import org.apache.poi.xssf.usermodel.XSSFDataValidationHelper;
  13. import org.apache.poi.xssf.usermodel.XSSFFont;
  14. import org.apache.poi.xssf.usermodel.XSSFRow;
  15. import org.apache.poi.xssf.usermodel.XSSFSheet;
  16. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  17. import org.springframework.stereotype.Component;
  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.lang.reflect.Field;
  21. import java.lang.reflect.Method;
  22. import java.text.DecimalFormat;
  23. import java.text.ParseException;
  24. import java.text.SimpleDateFormat;
  25. import java.util.ArrayList;
  26. import java.util.Date;
  27. import java.util.LinkedHashMap;
  28. import java.util.List;
  29. import java.util.Map;
  30. /**
  31. * Excel文件相关操作工具类
  32. *
  33. * @author kongwc
  34. * @create 2018-05-09 18:23
  35. */
  36. @Component
  37. public class PoiExcelUtil<T> {
  38. private static final String EXCEL_TEMPLATE = "classpath:/fileTemplate/EmailNoticeExcelTemplate.xlsx";
  39. private static final String CANCEL_ORDER_EXCEL_TEMPLATE = "classpath:/fileTemplate/CancelOrder.xlsx";
  40. /**
  41. * 没有定义转换时间格式
  42. *
  43. * @param clazz
  44. * @param stream
  45. * @return
  46. * @throws NoSuchFieldException
  47. * @throws InstantiationException
  48. * @throws IllegalAccessException
  49. * @throws ParseException
  50. * @throws IOException
  51. */
  52. public List<T> excelToList(Class<T> clazz, InputStream stream)
  53. throws NoSuchFieldException, InstantiationException, IllegalAccessException, ParseException, IOException {
  54. return excelToListWithDateForMate(clazz, stream, null);
  55. }
  56. /**
  57. * 定义转换时间格式
  58. *
  59. * @param clazz
  60. * @param stream
  61. * @param dateFormat
  62. * @return
  63. * @throws NoSuchFieldException
  64. * @throws InstantiationException
  65. * @throws IllegalAccessException
  66. * @throws ParseException
  67. * @throws IOException
  68. */
  69. public List<T> excelToList(Class<T> clazz, InputStream stream, String dateFormat)
  70. throws NoSuchFieldException, InstantiationException, IllegalAccessException, ParseException, IOException {
  71. return excelToListWithDateForMate(clazz, stream, dateFormat);
  72. }
  73. /**
  74. * 将文件流转成列表
  75. *
  76. * @param clazz 泛型类型
  77. * @param stream 文件流
  78. * @return 列表
  79. */
  80. public List<T> excelToListWithDateForMate(Class<T> clazz, InputStream stream, String dateFormat)
  81. throws IOException, IllegalAccessException, InstantiationException, NoSuchFieldException, ParseException,
  82. ParseException {
  83. if (dateFormat == null) {
  84. dateFormat = "yyyy-MM-dd HH:mm:ss";
  85. }
  86. if (stream == null) {
  87. return new ArrayList<>();
  88. }
  89. XSSFSheet xssfSheet = new XSSFWorkbook(stream).getSheetAt(0);
  90. //开始、结束行号
  91. int rowStart = xssfSheet.getFirstRowNum();
  92. int rowEnd = xssfSheet.getLastRowNum();
  93. XSSFRow columnNames = xssfSheet.getRow(rowStart);
  94. //列的开始,结束
  95. int cellStart = columnNames.getFirstCellNum();
  96. int cellEnd = columnNames.getLastCellNum();
  97. List<BasicNameValuePair> columnValues = new ArrayList<>();
  98. Field[] fields = clazz.getDeclaredFields();
  99. for (int k = cellStart; k < cellEnd; k++) {
  100. for (Field fieldItem : fields) {
  101. ColumnName cn = fieldItem.getAnnotation(ColumnName.class);
  102. if (cn != null) {
  103. String columnChineseName = fieldItem.getAnnotation(ColumnName.class).value();
  104. if (columnNames.getCell(k).getStringCellValue().equals(columnChineseName)) {
  105. columnValues.add(new BasicNameValuePair(fieldItem.getName(),
  106. fieldItem.getGenericType().toString()));
  107. break;
  108. }
  109. }
  110. }
  111. //导入的列与实际列不一致
  112. if (columnValues.size() <= k - cellStart) {
  113. return null;
  114. }
  115. }
  116. List<T> result = new ArrayList<>();
  117. for (int i = rowStart + 1; i <= rowEnd; i++) {
  118. T t = clazz.newInstance();
  119. XSSFRow row = xssfSheet.getRow(i);
  120. //不为空行
  121. if (row != null) {
  122. for (int k = cellStart; k < cellEnd; k++) {
  123. XSSFCell cell = row.getCell(k);
  124. Field field = clazz.getDeclaredField(columnValues.get(k - cellStart).getName());
  125. field.setAccessible(true);
  126. switch (columnValues.get(k - cellStart).getValue()) {
  127. case "class java.lang.String":
  128. field.set(t, getCellValue(cell));
  129. break;
  130. case "class java.lang.Integer":
  131. field.set(t, (int) cell.getNumericCellValue());
  132. break;
  133. case "int":
  134. field.set(t, (int) cell.getNumericCellValue());
  135. break;
  136. case "class java.lang.Boolean":
  137. if("是".equals(getCellValue(cell))){
  138. field.set(t, true);
  139. }
  140. else{
  141. field.set(t, false);
  142. }
  143. break;
  144. case "class java.util.Date":
  145. SimpleDateFormat format = new SimpleDateFormat(dateFormat);
  146. if (cell != null) {
  147. if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
  148. String dateStr = format.format(cell.getDateCellValue());
  149. field.set(t, format.parse(dateStr));
  150. } else {
  151. if (StringUtils.isBlank(cell.getStringCellValue())) {
  152. field.set(t, null);
  153. } else {
  154. field.set(t, format.parse(cell.getStringCellValue()));
  155. }
  156. }
  157. }
  158. break;
  159. default:
  160. break;
  161. }
  162. }
  163. }
  164. result.add(t);
  165. }
  166. return result;
  167. }
  168. /**
  169. * 获取单元格内容
  170. *
  171. * @param cell 单元格
  172. * @return 单元格的值
  173. */
  174. private Object getCellValue(XSSFCell cell) {
  175. Object value = null;
  176. if (cell != null) {
  177. switch (cell.getCellType()) {
  178. case XSSFCell.CELL_TYPE_STRING:
  179. value = cell.getStringCellValue();
  180. break;
  181. case XSSFCell.CELL_TYPE_NUMERIC:
  182. DecimalFormat df = new DecimalFormat("0");
  183. value = df.format(cell.getNumericCellValue()) + "";
  184. break;
  185. default:
  186. }
  187. }
  188. return value;
  189. }
  190. /**
  191. * 将列表转成文件流
  192. *
  193. * @param clazz
  194. * @param ts
  195. * @return
  196. * @throws Exception
  197. */
  198. public XSSFWorkbook listToExcel(Class<T> clazz, List<T> ts) throws Exception {
  199. return this.listToExcel(clazz, ts, null);
  200. }
  201. /**
  202. * 将列表转成文件流
  203. *
  204. * @param clazz
  205. * @param ts
  206. * @return
  207. * @throws Exception
  208. */
  209. public XSSFWorkbook listToExcel(Class<T> clazz, List<T> ts, String dataFormat) throws Exception {
  210. return this.listToExcel(clazz, ts, null, dataFormat);
  211. }
  212. /**
  213. * 将列表转成文件流
  214. *
  215. * @param clazz
  216. * @param ts
  217. * @param sheetName
  218. * @return
  219. * @throws Exception
  220. */
  221. public XSSFWorkbook listToExcel(Class<T> clazz, List<T> ts, String sheetName, String dateFormat) throws Exception {
  222. if (dateFormat == null) {
  223. dateFormat = "yyyy-MM-dd HH:mm";
  224. }
  225. XSSFWorkbook workbook = new XSSFWorkbook();
  226. this.createSheet(workbook, clazz, ts, (StringUtils.isBlank(sheetName)) ? "Sheet1" : sheetName, dateFormat, null, null);
  227. return workbook;
  228. }
  229. /**
  230. * 将列表转成文件流
  231. *
  232. * @param clazz
  233. * @param ts
  234. * @param sheetName
  235. * @return
  236. * @throws Exception
  237. */
  238. public XSSFWorkbook listToExcel(Class<T> clazz, List<T> ts, String sheetName, String dateFormat, SelectData selectData, List<Integer> lockedCols) throws Exception {
  239. if (dateFormat == null) {
  240. dateFormat = "yyyy-MM-dd HH:mm";
  241. }
  242. XSSFWorkbook workbook = new XSSFWorkbook();
  243. this.createSheet(workbook, clazz, ts, (StringUtils.isBlank(sheetName)) ? "Sheet1" : sheetName, dateFormat, selectData, lockedCols);
  244. return workbook;
  245. }
  246. /**
  247. * @param clazz
  248. * @param headerMap 表头字段属性集合 key 字段 value 字段含义(需有序)
  249. * @param ts
  250. * @param sheetName
  251. * @return
  252. * @throws Exception
  253. */
  254. public XSSFWorkbook listToExcelByMap(Class<T> clazz, Map<String, String> headerMap, List<T> ts, String sheetName)
  255. throws Exception {
  256. XSSFWorkbook workbook = new XSSFWorkbook();
  257. this.createSheetByMap(workbook, headerMap, ts, clazz, (StringUtils.isBlank(sheetName)) ? "Sheet1" : sheetName);
  258. return workbook;
  259. }
  260. /**
  261. * 创建Excel的Sheet
  262. *
  263. * @param workbook
  264. * @param clazz
  265. * @param data
  266. * @param sheetName
  267. * @param selectData 下拉值
  268. * @param lockedCols 锁定的列
  269. * @throws Exception
  270. */
  271. private void createSheet(XSSFWorkbook workbook, Class clazz, List data, String sheetName, String dateFormat, SelectData selectData, List<Integer> lockedCols)
  272. throws Exception {
  273. Field[] fields = clazz.getDeclaredFields();
  274. Map<String, String> columnInfos = new LinkedHashMap<>();
  275. //设置表头
  276. XSSFSheet sheet = workbook.createSheet(sheetName);
  277. XSSFRow headRow = sheet.createRow(0);
  278. for (int i = 0; i < fields.length; i++) {
  279. ColumnName cn = fields[i].getAnnotation(ColumnName.class);
  280. if (cn != null) {
  281. XSSFCell cell = headRow.createCell(i);
  282. sheet.setColumnWidth(i, 5000);
  283. //用easyExcel设置表头
  284. cell.setCellStyle(StyleUtil.buildDefaultCellStyle(workbook));
  285. String fieldType = fields[i].getGenericType().toString();
  286. cell.setCellValue(cn.value());
  287. columnInfos.put(fields[i].getName(), fieldType);
  288. }
  289. }
  290. //列的下拉选择赋值
  291. if(selectData != null){
  292. //生成下拉框
  293. String[] datas = selectData.getDatas();
  294. XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
  295. XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint) dvHelper.createExplicitListConstraint(datas);
  296. CellRangeAddressList addressList = new CellRangeAddressList(selectData.getFirstRow(), selectData.getLastRow(), selectData.getFirstCol(), selectData.getLastCol());
  297. XSSFDataValidation validation = (XSSFDataValidation) dvHelper.createValidation(
  298. dvConstraint, addressList);
  299. sheet.addValidationData(validation);
  300. }
  301. sheet.protectSheet("111");
  302. //XSSFCellStyle bodyStyle = workbook.createCellStyle();
  303. XSSFCellStyle lockStyle = workbook.createCellStyle();
  304. lockStyle.setLocked(true);
  305. //单元格不锁定的样式
  306. XSSFCellStyle unlockStyle = workbook.createCellStyle();
  307. unlockStyle.setLocked(false);
  308. //bodyStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  309. //设置内容
  310. for (int i = 0; i < data.size(); i++) {
  311. XSSFRow row = sheet.createRow(i + 1);
  312. int j = 0;
  313. for (Map.Entry<String, String> entry2 : columnInfos.entrySet()) {
  314. String columnName = entry2.getKey();
  315. String methodName = "get" + columnName.substring(0, 1).toUpperCase() + columnName.substring(1);
  316. Method method = clazz.getDeclaredMethod(methodName);
  317. Object value = method.invoke(data.get(i));
  318. XSSFCell cell = row.createCell(j);
  319. //判断是否要锁定列
  320. if(lockedCols != null && lockedCols.contains(j)){
  321. cell.setCellStyle(lockStyle);
  322. }else{
  323. cell.setCellStyle(unlockStyle);
  324. }
  325. j++;
  326. if (value != null) {
  327. switch (entry2.getValue()) {
  328. case "class java.lang.String":
  329. cell.setCellValue((String) value);
  330. break;
  331. case "int":
  332. cell.setCellValue((int) value);
  333. break;
  334. case "class java.lang.Integer":
  335. cell.setCellValue((int) value);
  336. break;
  337. case "class java.lang.Boolean":
  338. cell.setCellValue((boolean) value);
  339. break;
  340. case "class java.util.Date":
  341. //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
  342. SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
  343. cell.setCellValue(sdf.format((Date) value));
  344. break;
  345. default:
  346. }
  347. } else {
  348. cell.setCellValue("");
  349. }
  350. }
  351. }
  352. }
  353. /**
  354. * 创建Excel的Sheet
  355. *
  356. * @param workbook
  357. * @param headerMap 表头字段属性集合 key 字段 value 字段含义(需有序)
  358. * @param data
  359. * @param clazz
  360. * @param sheetName
  361. * @throws Exception boolean类型注意封装时的get/set方法
  362. */
  363. private void createSheetByMap(XSSFWorkbook workbook, Map<String, String> headerMap, List data, Class clazz,
  364. String sheetName) throws Exception {
  365. //样式
  366. XSSFFont font = workbook.createFont();
  367. //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  368. font.setColor(HSSFColor.BLUE.index);
  369. XSSFCellStyle headStyle = workbook.createCellStyle();
  370. headStyle.setFont(font);
  371. //headStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  372. //设置表头
  373. XSSFSheet sheet = workbook.createSheet(sheetName);
  374. XSSFRow headRow = sheet.createRow(0);
  375. int headerIdx = 0;
  376. for (Map.Entry<String, String> headerEntry : headerMap.entrySet()) {
  377. XSSFCell cell = headRow.createCell(headerIdx);
  378. cell.setCellType(XSSFCell.CELL_TYPE_STRING);
  379. sheet.setColumnWidth(headerIdx, 5000);
  380. cell.setCellStyle(headStyle);
  381. cell.setCellValue(headerEntry.getValue());
  382. headerIdx++;
  383. }
  384. XSSFCellStyle bodyStyle = workbook.createCellStyle();
  385. //bodyStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  386. //设置内容
  387. XSSFRow dataRow;
  388. Field field;
  389. Method method;
  390. XSSFCell cell;
  391. StringBuilder sb = new StringBuilder();
  392. for (int i = 0; i < data.size(); i++) {
  393. dataRow = sheet.createRow(i + 1);
  394. int j = 0;
  395. for (Map.Entry<String, String> headerEntry : headerMap.entrySet()) {
  396. field = clazz.getDeclaredField(headerEntry.getKey());
  397. sb.append("get").append(field.getName().substring(0, 1).toUpperCase())
  398. .append(field.getName().substring(1));
  399. method = clazz.getDeclaredMethod(sb.toString());
  400. sb.delete(0, sb.length());
  401. Object value = method.invoke(data.get(i));
  402. cell = dataRow.createCell(j++);
  403. cell.setCellStyle(bodyStyle);
  404. if (value != null) {
  405. switch (field.getType().getName()) {
  406. case "java.lang.String":
  407. cell.setCellValue((String) value);
  408. break;
  409. case "int":
  410. cell.setCellValue((int) value);
  411. break;
  412. case "java.lang.Integer":
  413. cell.setCellValue((int) value);
  414. break;
  415. case "java.lang.Boolean":
  416. cell.setCellValue((boolean) value);
  417. break;
  418. case "java.util.Date":
  419. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
  420. cell.setCellValue(sdf.format((Date) value));
  421. break;
  422. default:
  423. }
  424. } else {
  425. cell.setCellValue("");
  426. }
  427. }
  428. }
  429. }
  430. }

demo

  1. @GetMapping("/exportExcel")
  2. public void exportExcel(HttpServletResponse response) throws Exception {
  3. List<Person> list=new ArrayList<>();
  4. Person p1=new Person("末日");
  5. Person p2=new Person("神灵");
  6. list.add(p1);
  7. list.add(p2);
  8. String[] datas = new String[] {"部门","科室","岗位 "};
  9. SelectData selectData = new SelectData(datas, 1, 100, 0, 0);
  10. XSSFWorkbook applicantExcel = poiExcelUtil.listToExcel(Person.class, list, "kongtest", "yyyy-MM-dd", selectData);
  11. // 输出附件
  12. response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("下拉选择.xlsx", "UTF-8"));
  13. OutputStream outStream = response.getOutputStream();
  14. applicantExcel.write(outStream);
  15. outStream.flush();
  16. }
  17. 导入
  18. Map<String,Object> result = excelUtil.readExcel(file, new Person(),1);
  19. List<Person> excelImports = new ArrayList<>();
  20. Boolean flag = (Boolean) result.get("flag");
  21. Response response;
  22. List<Object> list;
  23. if(flag){
  24. list = (List<Object>) result.get("datas");
  25. if(list != null && list.size() > 0){
  26. list = (List<Object>) result.get("datas");
  27. }else{
  28. return BaseUtil.createResponse(ReturnCode.ERROR, "", Arrays.asList(ReturnMessage.IMPORT_NULL));
  29. }
  30. }else{
  31. return BaseUtil.createResponse(ReturnCode.ERROR, "", Arrays.asList(ReturnMessage.EXCEL_HEAD_ERROR));
  32. }

 

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号