ImportExcelUtil.java 14 KB

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