ImportExcelUtil.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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.Supplier;
  28. /**
  29. * @author phoenix
  30. * @Description 导入工具类
  31. * 2023/12/5
  32. */
  33. public class ImportExcelUtil {
  34. /**
  35. * 下载模板写入
  36. * @param obj
  37. * @return
  38. * @throws IOException
  39. */
  40. public static ByteArrayOutputStream writeTemplateSheet(Object obj) throws IOException {
  41. // 开始写入
  42. Workbook workbook = new XSSFWorkbook();
  43. // 创建一个工作表(sheet)
  44. String sheetName = "sheet1";
  45. Sheet sheet = workbook.createSheet(sheetName);
  46. List<ImportConfig> importConfigs = allFields(obj);
  47. // 表头
  48. createHead(workbook, sheet, importConfigs, 0);
  49. // 提示必填
  50. String content = "红色背景为必填项,导入时请删除本行。";
  51. createCautionHead(workbook, sheet, 1, content, importConfigs.size() - 1, 12);
  52. //写入文件
  53. ByteArrayOutputStream bot = new ByteArrayOutputStream();
  54. workbook.write(bot);
  55. return bot;
  56. }
  57. /**
  58. * 获取写入对象的所有字段
  59. * @param obj
  60. * @return
  61. */
  62. public static List<ImportConfig> allFields(Object obj) {
  63. List<ImportConfig> importConfigs = new ArrayList<>();
  64. if (obj == null) {
  65. return importConfigs;
  66. }
  67. Class<?> clazz = obj.getClass();
  68. Field[] fields = clazz.getDeclaredFields();
  69. int index = 0;
  70. for (int i = 0; i < fields.length; i++) {
  71. Field field = fields[i];
  72. ImportConfig importConfig = new ImportConfig();
  73. field.setAccessible(true); // 访问私有字段
  74. if (field.isAnnotationPresent(Required.class)) {
  75. Required required = field.getAnnotation(Required.class);
  76. Boolean value = required.value();
  77. importConfig.setRequired(value);
  78. }
  79. if (field.isAnnotationPresent(ExcelProperty.class)) {
  80. ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
  81. String[] annotationValues = excelProperty.value();
  82. importConfig.setLabel(annotationValues.length > 0 ? annotationValues[0] : "");
  83. }
  84. if (field.isAnnotationPresent(ExcelIgnore.class)) {
  85. continue;
  86. }
  87. importConfig.setFieldName(field.getName());
  88. importConfig.setSortCode(index++);
  89. importConfig.setWidth(0);
  90. importConfigs.add(importConfig);
  91. }
  92. return importConfigs;
  93. }
  94. /**
  95. * 写标题行
  96. * @param workbook
  97. * @param sheet
  98. * @param importConfigs
  99. * @param rowNumber
  100. */
  101. public static void createHead(Workbook workbook, Sheet sheet, List<ImportConfig> importConfigs, int rowNumber) {
  102. Font font = workbook.createFont();
  103. font.setFontName("宋体");
  104. font.setFontHeightInPoints((short)12);
  105. // 正常样式
  106. CellStyle normalCellStyle = workbook.createCellStyle();
  107. normalCellStyle.setFont(font); // 将字体应用到样式
  108. normalCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
  109. normalCellStyle.setAlignment(HorizontalAlignment.CENTER);
  110. // 必填样式
  111. CellStyle requiredCellStyle = workbook.createCellStyle();
  112. requiredCellStyle.setFont(font); // 将字体应用到样式
  113. requiredCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
  114. requiredCellStyle.setAlignment(HorizontalAlignment.CENTER);
  115. requiredCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());//设置背景颜色
  116. requiredCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);//设置填充模式
  117. // 所在行
  118. Row row = sheet.createRow(rowNumber);
  119. // 每一列
  120. for (ImportConfig importConfig : importConfigs){
  121. Cell cell = row.createCell(importConfig.getSortCode());
  122. String content = importConfig.getLabel();
  123. cell.setCellValue(content);
  124. if(ObjectUtils.isNotEmpty(importConfig.getRequired()) && importConfig.getRequired()){
  125. cell.setCellStyle(requiredCellStyle);
  126. }
  127. if(ObjectUtils.isEmpty(importConfig.getRequired()) || !importConfig.getRequired()) {
  128. cell.setCellStyle(normalCellStyle);
  129. }
  130. }
  131. }
  132. /**
  133. * 写提示行
  134. * @param workbook
  135. * @param sheet
  136. * @param rowNumber
  137. * @param content
  138. * @param lastCol
  139. * @param size
  140. */
  141. public static void createCautionHead(Workbook workbook, Sheet sheet, int rowNumber, String content, int lastCol, int size) {
  142. Font font = workbook.createFont();
  143. font.setFontName("宋体");
  144. font.setFontHeightInPoints((short)size);
  145. font.setColor(IndexedColors.RED.getIndex());
  146. CellStyle cellStyle = workbook.createCellStyle();
  147. cellStyle.setFont(font); // 将字体应用到样式
  148. Row row = sheet.createRow(rowNumber);
  149. Cell cell = row.createCell(0);
  150. cell.setCellValue(content);
  151. cell.setCellStyle(cellStyle);
  152. sheet.addMergedRegion(new CellRangeAddress(rowNumber, rowNumber, 0, lastCol));
  153. }
  154. /**
  155. * 验证子表字段值的合理性并转换为对应的主键
  156. * @param getter
  157. * @param fieldName
  158. * @param string2Long
  159. * @param setter
  160. * @param sb
  161. * @param i
  162. * @return
  163. */
  164. public static boolean validateAndSetString2LongField(Supplier<String> getter,
  165. String fieldName,
  166. Map<String, Long> string2Long,
  167. Consumer<Long> setter,
  168. StringBuilder sb, int i) {
  169. String value = getter.get();
  170. if (value != null && !value.trim().isEmpty()) {
  171. Long sublistValue = string2Long.get(value);
  172. if (sublistValue != null) {
  173. setter.accept(sublistValue);
  174. return false;
  175. } else {
  176. sb.append("第");
  177. sb.append(i);
  178. sb.append("行的");
  179. sb.append(fieldName);
  180. sb.append("列的值不存在于系统对应基础数据中,请到基础数据维护");
  181. return true;
  182. }
  183. }
  184. return false; // 字段为空,不进行验证
  185. }
  186. /**
  187. * 验证boolean值的合理性并转换为数值
  188. * @param getter
  189. * @param fieldName
  190. * @param setter
  191. * @param sb
  192. * @param i
  193. * @return
  194. */
  195. public static boolean validateAndSetBooleanField(Supplier<String> getter,
  196. String fieldName,
  197. Consumer<Integer> setter,
  198. StringBuilder sb, int i) {
  199. String value = getter.get();
  200. if (value != null && !value.trim().isEmpty()) {
  201. Integer booleanValue = YesOrNoEnum.getCode(value);
  202. if (booleanValue != null) {
  203. setter.accept(booleanValue);
  204. return false;
  205. } else {
  206. sb.append("第");
  207. sb.append(i);
  208. sb.append("行的");
  209. sb.append(fieldName);
  210. sb.append("列的值不符合,该列的值只能为是或否");
  211. return true;
  212. }
  213. }
  214. return false; // 字段为空,不进行验证
  215. }
  216. /**
  217. * 验证字典值的合理性并转换为字典的code
  218. * @param getter
  219. * @param prefix
  220. * @param fieldName
  221. * @param dictionary
  222. * @param setter
  223. * @param sb
  224. * @param i
  225. * @return
  226. */
  227. public static boolean validateAndSetDictionaryField(Supplier<String> getter,
  228. String prefix,
  229. String fieldName,
  230. Map<String, String> dictionary,
  231. Consumer<String> setter,
  232. StringBuilder sb, int i) {
  233. String value = getter.get();
  234. if (value != null && !value.trim().isEmpty()) {
  235. String dictValue = dictionary.get(prefix + value.trim());
  236. if (dictValue != null && !dictValue.trim().isEmpty()) {
  237. setter.accept(dictValue.trim());
  238. return false;
  239. } else {
  240. sb.append("第");
  241. sb.append(i);
  242. sb.append("行的");
  243. sb.append(fieldName);
  244. sb.append("列的值不存在于字典中,请到字典中维护");
  245. return true;
  246. }
  247. }
  248. return false; // 字段为空,不进行验证
  249. }
  250. /**
  251. * 验证枚举值的合理性并转换为枚举的code
  252. * @param getter
  253. * @param fieldName
  254. * @param setter
  255. * @param sb
  256. * @param i
  257. * @return
  258. */
  259. public static <E extends Enum<E>> boolean validateAndSetEnumField(Supplier<String> getter,
  260. String fieldName,
  261. Map<String, Integer> enumMap,
  262. Consumer<Integer> setter,
  263. StringBuilder sb, int i) {
  264. String value = getter.get();
  265. if (value != null && !value.trim().isEmpty()) {
  266. Integer enumValue = enumMap.get(value);
  267. if (enumValue != null) {
  268. setter.accept(enumValue);
  269. return false;
  270. } else {
  271. sb.append("第");
  272. sb.append(i);
  273. sb.append("行的");
  274. sb.append(fieldName);
  275. sb.append("列的值不存在于枚举值中,请到枚举值中维护");
  276. return true;
  277. }
  278. }
  279. return false; // 字段为空,不进行验证
  280. }
  281. /**
  282. * 获取所有的字典值映射
  283. * @param codeList
  284. * @return
  285. */
  286. public static Map<String, String> initDictionary(List<String> codeList, DictionaryitemMapper dictionaryitemMapper, DictionarydetailMapper dictionarydetailMapper) {
  287. List<DictionaryDetail> detailList = dictionarydetailMapper.selectJoinList(DictionaryDetail.class,
  288. new MPJLambdaWrapper<DictionaryDetail>()
  289. .select(DictionaryDetail::getId)
  290. .select(DictionaryDetail.class, x -> VoToColumnUtil.fieldsToColumns(DictionaryDetail.class).contains(x.getProperty()))
  291. .leftJoin(DictionaryItem.class, DictionaryItem::getId, DictionaryDetail::getItemId)
  292. .in(DictionaryItem::getCode, codeList)
  293. );
  294. List<DictionaryItem> dictionaryItemList = dictionaryitemMapper.selectList(
  295. new QueryWrapper<DictionaryItem>().lambda()
  296. .eq(DictionaryItem::getDeleteMark, DeleteMark.NODELETE.getCode())
  297. );
  298. Map<Long, String> itemMap = new HashMap<>();
  299. for (DictionaryItem dictionaryItem : dictionaryItemList) {
  300. itemMap.put(dictionaryItem.getId(), dictionaryItem.getCode());
  301. }
  302. Map<String, String> resultMap = new HashMap<>();
  303. for (DictionaryDetail dictionaryDetail : detailList) {
  304. resultMap.put(itemMap.get(dictionaryDetail.getItemId()) + dictionaryDetail.getName(), dictionaryDetail.getCode());
  305. }
  306. return resultMap;
  307. }
  308. /**
  309. * 判断属性是否为必填属性
  310. * @param instance
  311. * @param sb
  312. * @param i
  313. * @return
  314. * @throws IllegalAccessException
  315. */
  316. public static boolean isRequiredFieldsFilled(Object instance,
  317. StringBuilder sb,
  318. int i)
  319. throws IllegalAccessException {
  320. if (instance == null) {
  321. return true; // 如果对象本身为 null,则认为没有通过验证
  322. }
  323. for (Field field : instance.getClass().getDeclaredFields()) {
  324. Required required = field.getAnnotation(Required.class);
  325. if (required != null) { // 如果字段被 @Required 标记
  326. field.setAccessible(true); // 允许访问私有字段
  327. Object value = field.get(instance); // 获取字段的值
  328. if (value == null || (value instanceof String && ((String) value).trim().isEmpty())) {
  329. sb.append("第");
  330. sb.append(i);
  331. sb.append("行的");
  332. if (field.isAnnotationPresent(ExcelProperty.class)) {
  333. ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
  334. String[] annotationValues = excelProperty.value();
  335. sb.append(annotationValues.length > 0 ? annotationValues[0] : "");
  336. }
  337. sb.append("列的值为必填");
  338. return true; // 如果任何必需字段为空,则返回 true
  339. }
  340. }
  341. }
  342. return false; // 所有必需字段都不为空
  343. }
  344. }