ImportExcelUtil.java 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. package com.xjrsoft.module.veb.util;
  2. import com.alibaba.excel.annotation.ExcelIgnore;
  3. import com.alibaba.excel.annotation.ExcelProperty;
  4. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  5. import com.github.yulichang.wrapper.MPJLambdaWrapper;
  6. import com.xjrsoft.common.annotation.Required;
  7. import com.xjrsoft.common.enums.DeleteMark;
  8. import com.xjrsoft.common.enums.YesOrNoEnum;
  9. import com.xjrsoft.common.utils.VoToColumnUtil;
  10. import com.xjrsoft.module.generator.entity.ImportConfig;
  11. import com.xjrsoft.module.system.entity.DictionaryDetail;
  12. import com.xjrsoft.module.system.entity.DictionaryItem;
  13. import com.xjrsoft.module.system.mapper.DictionarydetailMapper;
  14. import com.xjrsoft.module.system.mapper.DictionaryitemMapper;
  15. import org.apache.commons.lang3.ObjectUtils;
  16. import org.apache.poi.ss.usermodel.*;
  17. import org.apache.poi.ss.util.CellRangeAddress;
  18. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  19. import java.io.ByteArrayOutputStream;
  20. import java.io.IOException;
  21. import java.lang.reflect.Field;
  22. import java.util.ArrayList;
  23. import java.util.HashMap;
  24. import java.util.List;
  25. import java.util.Map;
  26. import java.util.function.Consumer;
  27. import java.util.function.Function;
  28. import java.util.function.Supplier;
  29. /**
  30. * @author phoenix
  31. * @Description 导入工具类
  32. * 2023/12/5
  33. */
  34. public class ImportExcelUtil {
  35. /**
  36. * 下载模板写入
  37. * @param obj
  38. * @return
  39. * @throws IOException
  40. */
  41. public static ByteArrayOutputStream writeTemplateSheet(Object obj) throws IOException {
  42. // 开始写入
  43. Workbook workbook = new XSSFWorkbook();
  44. // 创建一个工作表(sheet)
  45. String sheetName = "sheet1";
  46. Sheet sheet = workbook.createSheet(sheetName);
  47. List<ImportConfig> importConfigs = allFields(obj);
  48. // 表头
  49. createHead(workbook, sheet, importConfigs, 0);
  50. // 提示必填
  51. String content = "红色背景为必填项,导入时请删除本行。";
  52. createCautionHead(workbook, sheet, 1, content, importConfigs.size() - 1, 12, IndexedColors.RED.getIndex());
  53. //写入文件
  54. ByteArrayOutputStream bot = new ByteArrayOutputStream();
  55. workbook.write(bot);
  56. return bot;
  57. }
  58. /**
  59. * 获取写入对象的所有字段
  60. * @param obj
  61. * @return
  62. */
  63. public static List<ImportConfig> allFields(Object obj) {
  64. List<ImportConfig> importConfigs = new ArrayList<>();
  65. if (obj == null) {
  66. return importConfigs;
  67. }
  68. Class<?> clazz = obj.getClass();
  69. Field[] fields = clazz.getDeclaredFields();
  70. int index = 0;
  71. for (int i = 0; i < fields.length; i++) {
  72. Field field = fields[i];
  73. ImportConfig importConfig = new ImportConfig();
  74. field.setAccessible(true); // 访问私有字段
  75. if (field.isAnnotationPresent(Required.class)) {
  76. Required required = field.getAnnotation(Required.class);
  77. Boolean value = required.value();
  78. importConfig.setRequired(value);
  79. }
  80. if (field.isAnnotationPresent(ExcelProperty.class)) {
  81. ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
  82. String[] annotationValues = excelProperty.value();
  83. importConfig.setLabel(annotationValues.length > 0 ? annotationValues[0] : "");
  84. }
  85. if (field.isAnnotationPresent(ExcelIgnore.class)) {
  86. continue;
  87. }
  88. importConfig.setFieldName(field.getName());
  89. importConfig.setSortCode(index++);
  90. importConfig.setWidth(0);
  91. importConfigs.add(importConfig);
  92. }
  93. return importConfigs;
  94. }
  95. /**
  96. * 写大标题行
  97. * @param workbook
  98. * @param sheet
  99. * @param bigHead
  100. * @param rowNumber
  101. * @param lastCol
  102. */
  103. public static void createBigHead(Workbook workbook, Sheet sheet, String bigHead, int rowNumber, int lastCol) {
  104. Font font = workbook.createFont();
  105. font.setFontName("宋体");
  106. font.setFontHeightInPoints((short)18);
  107. // 正常样式
  108. CellStyle normalCellStyle = workbook.createCellStyle();
  109. normalCellStyle.setFont(font); // 将字体应用到样式
  110. normalCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
  111. normalCellStyle.setAlignment(HorizontalAlignment.CENTER);
  112. // 设置边框样式为细线
  113. normalCellStyle.setBorderTop(BorderStyle.THIN);
  114. normalCellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex()); // 设置顶部边框颜色
  115. normalCellStyle.setBorderBottom(BorderStyle.THIN);
  116. normalCellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex()); // 设置底部边框颜色
  117. normalCellStyle.setBorderLeft(BorderStyle.THIN);
  118. normalCellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex()); // 设置左边框颜色
  119. normalCellStyle.setBorderRight(BorderStyle.THIN);
  120. normalCellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex()); // 设置右边框颜色
  121. // 所在行
  122. Row row = sheet.createRow(rowNumber);
  123. Cell cell = row.createCell(0);
  124. cell.setCellValue(bigHead);
  125. cell.setCellStyle(normalCellStyle);
  126. sheet.addMergedRegion(new CellRangeAddress(rowNumber, rowNumber, 0, lastCol));
  127. }
  128. /**
  129. * 写标题行
  130. * @param workbook
  131. * @param sheet
  132. * @param importConfigs
  133. * @param rowNumber
  134. */
  135. public static void createHead(Workbook workbook, Sheet sheet, List<ImportConfig> importConfigs, int rowNumber) {
  136. Font font = workbook.createFont();
  137. font.setFontName("宋体");
  138. font.setFontHeightInPoints((short)12);
  139. // 正常样式
  140. CellStyle normalCellStyle = workbook.createCellStyle();
  141. normalCellStyle.setFont(font); // 将字体应用到样式
  142. normalCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
  143. normalCellStyle.setAlignment(HorizontalAlignment.CENTER);
  144. // 设置边框样式为细线
  145. normalCellStyle.setBorderTop(BorderStyle.THIN);
  146. normalCellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex()); // 设置顶部边框颜色
  147. normalCellStyle.setBorderBottom(BorderStyle.THIN);
  148. normalCellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex()); // 设置底部边框颜色
  149. normalCellStyle.setBorderLeft(BorderStyle.THIN);
  150. normalCellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex()); // 设置左边框颜色
  151. normalCellStyle.setBorderRight(BorderStyle.THIN);
  152. normalCellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex()); // 设置右边框颜色
  153. // 必填样式
  154. CellStyle requiredCellStyle = workbook.createCellStyle();
  155. requiredCellStyle.setFont(font); // 将字体应用到样式
  156. requiredCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
  157. requiredCellStyle.setAlignment(HorizontalAlignment.CENTER);
  158. requiredCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());//设置背景颜色
  159. requiredCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);//设置填充模式
  160. // 设置边框样式为细线
  161. requiredCellStyle.setBorderTop(BorderStyle.THIN);
  162. requiredCellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex()); // 设置顶部边框颜色
  163. requiredCellStyle.setBorderBottom(BorderStyle.THIN);
  164. requiredCellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex()); // 设置底部边框颜色
  165. requiredCellStyle.setBorderLeft(BorderStyle.THIN);
  166. requiredCellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex()); // 设置左边框颜色
  167. requiredCellStyle.setBorderRight(BorderStyle.THIN);
  168. requiredCellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex()); // 设置右边框颜色
  169. // 所在行
  170. Row row = sheet.createRow(rowNumber);
  171. // 每一列
  172. for (ImportConfig importConfig : importConfigs){
  173. Cell cell = row.createCell(importConfig.getSortCode());
  174. String content = importConfig.getLabel();
  175. cell.setCellValue(content);
  176. if(ObjectUtils.isNotEmpty(importConfig.getRequired()) && importConfig.getRequired()){
  177. cell.setCellStyle(requiredCellStyle);
  178. }
  179. if(ObjectUtils.isEmpty(importConfig.getRequired()) || !importConfig.getRequired()) {
  180. cell.setCellStyle(normalCellStyle);
  181. }
  182. }
  183. }
  184. /**
  185. * 写单格
  186. * @param workbook
  187. * @param sheet
  188. * @param content
  189. * @param rowNumber
  190. * @param starRow
  191. * @param endRow
  192. * @param startcol
  193. * @param lastCol
  194. * @param fontSize
  195. * @param indexedColor
  196. */
  197. public static void createOneCell(Workbook workbook, Sheet sheet, String content, int rowNumber, int starRow, int endRow, int startcol, int lastCol, short fontSize, short indexedColor, HorizontalAlignment horizontalAlignment) {
  198. Font font = workbook.createFont();
  199. font.setFontName("宋体");
  200. font.setFontHeightInPoints(fontSize);
  201. font.setColor(indexedColor);
  202. // 正常样式
  203. CellStyle normalCellStyle = workbook.createCellStyle();
  204. normalCellStyle.setFont(font); // 将字体应用到样式
  205. normalCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
  206. normalCellStyle.setAlignment(horizontalAlignment);
  207. // 设置边框样式为细线
  208. normalCellStyle.setBorderTop(BorderStyle.THIN);
  209. normalCellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex()); // 设置顶部边框颜色
  210. normalCellStyle.setBorderBottom(BorderStyle.THIN);
  211. normalCellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex()); // 设置底部边框颜色
  212. normalCellStyle.setBorderLeft(BorderStyle.THIN);
  213. normalCellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex()); // 设置左边框颜色
  214. normalCellStyle.setBorderRight(BorderStyle.THIN);
  215. normalCellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex()); // 设置右边框颜色
  216. // 所在行
  217. Row row = sheet.createRow(rowNumber);
  218. Cell cell = row.createCell(0);
  219. cell.setCellValue(content);
  220. cell.setCellStyle(normalCellStyle);
  221. sheet.addMergedRegion(new CellRangeAddress(starRow, endRow, startcol, lastCol));
  222. }
  223. /**
  224. * 写提示行
  225. * @param workbook
  226. * @param sheet
  227. * @param rowNumber
  228. * @param content
  229. * @param lastCol
  230. * @param fontSize
  231. */
  232. public static void createCautionHead(Workbook workbook, Sheet sheet, int rowNumber, String content, int lastCol, int fontSize, short indexedColor) {
  233. Font font = workbook.createFont();
  234. font.setFontName("宋体");
  235. font.setFontHeightInPoints((short)fontSize);
  236. font.setColor(indexedColor);
  237. // font.setColor(IndexedColors.RED.getIndex());
  238. CellStyle cellStyle = workbook.createCellStyle();
  239. cellStyle.setFont(font); // 将字体应用到样式
  240. cellStyle.setBorderTop(BorderStyle.THIN);
  241. cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex()); // 设置顶部边框颜色
  242. cellStyle.setBorderBottom(BorderStyle.THIN);
  243. cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex()); // 设置底部边框颜色
  244. cellStyle.setBorderLeft(BorderStyle.THIN);
  245. cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex()); // 设置左边框颜色
  246. cellStyle.setBorderRight(BorderStyle.THIN);
  247. cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex()); // 设置右边框颜色
  248. Row row = sheet.createRow(rowNumber);
  249. Cell cell = row.createCell(0);
  250. cell.setCellValue(content);
  251. cell.setCellStyle(cellStyle);
  252. sheet.addMergedRegion(new CellRangeAddress(rowNumber, rowNumber, 0, lastCol));
  253. }
  254. /**
  255. * 验证子表字段值的合理性并转换为对应的主键
  256. * @param getter
  257. * @param fieldName
  258. * @param string2Long
  259. * @param setter
  260. * @param sb
  261. * @param i
  262. * @return
  263. */
  264. public static boolean validateAndSetString2LongField(Supplier<String> getter,
  265. String fieldName,
  266. Map<String, Long> string2Long,
  267. Consumer<Long> setter,
  268. StringBuilder sb, int i) {
  269. String value = getter.get();
  270. if (value != null && !value.trim().isEmpty()) {
  271. Long sublistValue = string2Long.get(value);
  272. if (sublistValue != null) {
  273. setter.accept(sublistValue);
  274. return false;
  275. } else {
  276. sb.append("第");
  277. sb.append(i);
  278. sb.append("行的");
  279. sb.append(fieldName);
  280. sb.append("列的值不存在于系统对应基础数据中,请到基础数据维护");
  281. return true;
  282. }
  283. }
  284. return false; // 字段为空,不进行验证
  285. }
  286. /**
  287. * 验证boolean值的合理性并转换为数值
  288. * @param getter
  289. * @param fieldName
  290. * @param setter
  291. * @param sb
  292. * @param i
  293. * @return
  294. */
  295. public static boolean validateAndSetBooleanField(Supplier<String> getter,
  296. String fieldName,
  297. Consumer<Integer> setter,
  298. StringBuilder sb, int i) {
  299. String value = getter.get();
  300. if (value != null && !value.trim().isEmpty()) {
  301. Integer booleanValue = YesOrNoEnum.getCode(value);
  302. if (booleanValue != null) {
  303. setter.accept(booleanValue);
  304. return false;
  305. } else {
  306. sb.append("第");
  307. sb.append(i);
  308. sb.append("行的");
  309. sb.append(fieldName);
  310. sb.append("列的值不符合,该列的值只能为是或否");
  311. return true;
  312. }
  313. }
  314. return false; // 字段为空,不进行验证
  315. }
  316. /**
  317. * 验证字典值的合理性并转换为字典的code
  318. * @param getter
  319. * @param prefix
  320. * @param fieldName
  321. * @param dictionary
  322. * @param setter
  323. * @param sb
  324. * @param i
  325. * @return
  326. */
  327. public static boolean validateAndSetDictionaryField(Supplier<String> getter,
  328. String prefix,
  329. String fieldName,
  330. Map<String, String> dictionary,
  331. Consumer<String> setter,
  332. StringBuilder sb, int i) {
  333. String value = getter.get();
  334. if (value != null && !value.trim().isEmpty()) {
  335. String dictValue = dictionary.get(prefix + value.trim());
  336. if (dictValue != null && !dictValue.trim().isEmpty()) {
  337. setter.accept(dictValue.trim());
  338. return false;
  339. } else {
  340. sb.append("第");
  341. sb.append(i);
  342. sb.append("行的");
  343. sb.append(fieldName);
  344. sb.append("列的值不存在于字典中,请到字典中维护");
  345. return true;
  346. }
  347. }
  348. return false; // 字段为空,不进行验证
  349. }
  350. /**
  351. * 验证枚举值的合理性并转换为枚举的code
  352. * @param getter
  353. * @param fieldName
  354. * @param setter
  355. * @param sb
  356. * @param i
  357. * @return
  358. */
  359. public static <E extends Enum<E>> boolean validateAndSetEnumField(Supplier<String> getter,
  360. String fieldName,
  361. Map<String, Integer> enumMap,
  362. Consumer<Integer> setter,
  363. StringBuilder sb, int i) {
  364. String value = getter.get();
  365. if (value != null && !value.trim().isEmpty()) {
  366. Integer enumValue = enumMap.get(value);
  367. if (enumValue != null) {
  368. setter.accept(enumValue);
  369. return false;
  370. } else {
  371. sb.append("第");
  372. sb.append(i);
  373. sb.append("行的");
  374. sb.append(fieldName);
  375. sb.append("列的值不存在于枚举值中,请到枚举值中维护");
  376. return true;
  377. }
  378. }
  379. return false; // 字段为空,不进行验证
  380. }
  381. /**
  382. * 获取所有的字典值映射
  383. * @param codeList
  384. * @return
  385. */
  386. public static Map<String, String> initDictionary(List<String> codeList, DictionaryitemMapper dictionaryitemMapper, DictionarydetailMapper dictionarydetailMapper) {
  387. List<DictionaryDetail> detailList = dictionarydetailMapper.selectJoinList(DictionaryDetail.class,
  388. new MPJLambdaWrapper<DictionaryDetail>()
  389. .select(DictionaryDetail::getId)
  390. .select(DictionaryDetail.class, x -> VoToColumnUtil.fieldsToColumns(DictionaryDetail.class).contains(x.getProperty()))
  391. .leftJoin(DictionaryItem.class, DictionaryItem::getId, DictionaryDetail::getItemId)
  392. .in(DictionaryItem::getCode, codeList)
  393. );
  394. List<DictionaryItem> dictionaryItemList = dictionaryitemMapper.selectList(
  395. new QueryWrapper<DictionaryItem>().lambda()
  396. .eq(DictionaryItem::getDeleteMark, DeleteMark.NODELETE.getCode())
  397. );
  398. Map<Long, String> itemMap = new HashMap<>();
  399. for (DictionaryItem dictionaryItem : dictionaryItemList) {
  400. itemMap.put(dictionaryItem.getId(), dictionaryItem.getCode());
  401. }
  402. Map<String, String> resultMap = new HashMap<>();
  403. for (DictionaryDetail dictionaryDetail : detailList) {
  404. resultMap.put(itemMap.get(dictionaryDetail.getItemId()) + dictionaryDetail.getName(), dictionaryDetail.getCode());
  405. }
  406. return resultMap;
  407. }
  408. /**
  409. * 判断属性是否为必填属性
  410. * @param instance
  411. * @param sb
  412. * @param i
  413. * @return
  414. * @throws IllegalAccessException
  415. */
  416. public static boolean isRequiredFieldsFilled(Object instance,
  417. StringBuilder sb,
  418. int i)
  419. throws IllegalAccessException {
  420. if (instance == null) {
  421. return true; // 如果对象本身为 null,则认为没有通过验证
  422. }
  423. for (Field field : instance.getClass().getDeclaredFields()) {
  424. Required required = field.getAnnotation(Required.class);
  425. if (required != null) { // 如果字段被 @Required 标记
  426. field.setAccessible(true); // 允许访问私有字段
  427. Object value = field.get(instance); // 获取字段的值
  428. if (value == null || (value instanceof String && ((String) value).trim().isEmpty())) {
  429. sb.append("第");
  430. sb.append(i);
  431. sb.append("行的");
  432. if (field.isAnnotationPresent(ExcelProperty.class)) {
  433. ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
  434. String[] annotationValues = excelProperty.value();
  435. sb.append(annotationValues.length > 0 ? annotationValues[0] : "");
  436. }
  437. sb.append("列的值为必填");
  438. return true; // 如果任何必需字段为空,则返回 true
  439. }
  440. }
  441. }
  442. return false; // 所有必需字段都不为空
  443. }
  444. /**
  445. * 将对象列表转换为二维字符串列表
  446. * @param dataList 数据对象列表
  447. * @param mappers 字段提取函数数组
  448. * @param <T> 数据对象类型
  449. * @return 二维字符串列表
  450. */
  451. @SafeVarargs
  452. public static <T> List<List<String>> convertToDataList(List<T> dataList, Function<T, String>... mappers) {
  453. List<List<String>> result = new ArrayList<>();
  454. for (T data : dataList) {
  455. List<String> row = new ArrayList<>();
  456. for (Function<T, String> mapper : mappers) {
  457. row.add(mapper.apply(data));
  458. }
  459. result.add(row);
  460. }
  461. return result;
  462. }
  463. public static List<ImportConfig> getAllFieldCN(Class<?> clazz) {
  464. List<ImportConfig> importConfigs = new ArrayList<>();
  465. Field[] fields = clazz.getDeclaredFields();
  466. int index = 0;
  467. for (int i = 0; i < fields.length; i++) {
  468. Field field = fields[i];
  469. ImportConfig importConfig = new ImportConfig();
  470. field.setAccessible(true); // 访问私有字段
  471. if (field.isAnnotationPresent(Required.class)) {
  472. Required required = field.getAnnotation(Required.class);
  473. boolean value = required.value();
  474. importConfig.setRequired(value);
  475. }
  476. if (field.isAnnotationPresent(ExcelProperty.class)) {
  477. ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
  478. String[] annotationValues = excelProperty.value();
  479. importConfig.setLabel(annotationValues.length > 0 ? annotationValues[0] : "");
  480. }
  481. if (field.isAnnotationPresent(ExcelIgnore.class)) {
  482. continue;
  483. }
  484. importConfig.setFieldName(field.getName());
  485. importConfig.setSortCode(index++);
  486. importConfig.setWidth(0);
  487. importConfigs.add(importConfig);
  488. }
  489. return importConfigs;
  490. }
  491. }