ExcelTool.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. package jnpf.base.util;
  2. import cn.afterturn.easypoi.excel.ExcelExportUtil;
  3. import cn.afterturn.easypoi.excel.entity.ExportParams;
  4. import cn.afterturn.easypoi.excel.entity.ImportParams;
  5. import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
  6. import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
  7. import jnpf.base.ActionResult;
  8. import jnpf.base.vo.DownloadVO;
  9. import jnpf.config.ConfigValueUtil;
  10. import jnpf.constant.FileTypeConstant;
  11. import jnpf.constant.MsgCode;
  12. import jnpf.entity.FileParameter;
  13. import jnpf.excel.ExcelExportStyler;
  14. import jnpf.excel.ExcelHelper;
  15. import jnpf.exception.DataException;
  16. import jnpf.model.ExcelModel;
  17. import jnpf.model.ExcelViewFieldModel;
  18. import jnpf.util.DateUtil;
  19. import jnpf.util.*;
  20. import jnpf.util.context.SpringContext;
  21. import lombok.Cleanup;
  22. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  23. import org.apache.poi.ss.usermodel.*;
  24. import org.apache.poi.ss.util.CellRangeAddress;
  25. import org.apache.poi.ss.util.CellRangeAddressList;
  26. import org.apache.poi.xssf.usermodel.*;
  27. import org.dromara.x.file.storage.core.FileInfo;
  28. import org.springframework.web.multipart.MultipartFile;
  29. import java.io.File;
  30. import java.io.IOException;
  31. import java.io.InputStream;
  32. import java.util.ArrayList;
  33. import java.util.HashMap;
  34. import java.util.List;
  35. import java.util.Map;
  36. /**
  37. * 系统模块得导入导出公共方法
  38. *
  39. * @author JNPF开发平台组
  40. * @version v5.0.0
  41. * @copyright 引迈信息技术有限公司
  42. * @date 2024/5/31 13:50:52
  43. */
  44. public class ExcelTool {
  45. private static ConfigValueUtil configValueUtil = SpringContext.getBean(ConfigValueUtil.class);
  46. public static ActionResult<Object> uploader() {
  47. List<MultipartFile> list = UpUtil.getFileAll();
  48. MultipartFile file = list.get(0);
  49. if (file.getOriginalFilename().endsWith(".xlsx") || file.getOriginalFilename().endsWith(".xls")) {
  50. String fileName = XSSEscape.escape(RandomUtil.uuId() + "." + UpUtil.getFileType(file));
  51. //上传文件
  52. FileInfo fileInfo = FileUploadUtils.uploadFile(new FileParameter(FileTypeConstant.TEMPORARY, fileName), file);
  53. DownloadVO vo = DownloadVO.builder().build();
  54. vo.setName(fileInfo.getFilename());
  55. return ActionResult.success(vo);
  56. } else {
  57. return ActionResult.fail(MsgCode.ETD110.get());
  58. }
  59. }
  60. public static DownloadVO getImportTemplate(String temporaryFilePath, String templateName, Map<String, String> keyMap, List<Map<String, Object>> list, ExcelModel excelModel) {
  61. DownloadVO vo = DownloadVO.builder().build();
  62. //主表对象
  63. List<ExcelExportEntity> entitys = new ArrayList<>();
  64. //以下添加字段
  65. for (String key : keyMap.keySet()) {
  66. String name = keyMap.get(key);
  67. entitys.add(new ExcelExportEntity(name + "(" + key + ")", key));
  68. }
  69. ExportParams exportParams = new ExportParams(null, templateName);
  70. exportParams.setType(ExcelType.XSSF);
  71. try {
  72. @Cleanup Workbook workbook = new HSSFWorkbook();
  73. if (entitys.size() > 0) {
  74. if (list.size() == 0) {
  75. list.add(new HashMap<>());
  76. }
  77. ExcelHelper helper = new ExcelHelper();
  78. exportParams.setStyle(ExcelExportStyler.class);
  79. workbook = ExcelExportUtil.exportExcel(exportParams, entitys, list);
  80. helper.init(workbook, exportParams, entitys, excelModel);
  81. helper.doPreHandle();
  82. helper.doPostHandle();
  83. }
  84. String fileName = templateName + "导入模板" + ".xls";
  85. MultipartFile multipartFile = ExcelUtil.workbookToCommonsMultipartFile(workbook, fileName);
  86. multipartFile = setTopTitle(excelModel, multipartFile, fileName);
  87. FileInfo fileInfo = FileUploadUtils.uploadFile(new FileParameter(temporaryFilePath, fileName), multipartFile);
  88. vo.setName(fileInfo.getFilename());
  89. vo.setUrl(UploaderUtil.uploaderFile(fileInfo.getFilename() + "#" + FileTypeConstant.TEMPORARY) + "&name=" + fileName);
  90. } catch (Exception e) {
  91. e.printStackTrace();
  92. }
  93. return vo;
  94. }
  95. /**
  96. * 设置表头(翻译标记用。)
  97. *
  98. * @param excelModel
  99. * @param multipartFile
  100. * @param fileName
  101. * @return
  102. * @throws IOException
  103. */
  104. private static MultipartFile setTopTitle(ExcelModel excelModel, MultipartFile multipartFile, String fileName) throws IOException {
  105. if (excelModel.isHasHeader()) {
  106. InputStream inputStream = multipartFile.getInputStream();
  107. @Cleanup XSSFWorkbook workbook2 = new XSSFWorkbook(inputStream);
  108. XSSFSheet sheetAt = workbook2.getSheetAt(0);
  109. short lastCellNum = sheetAt.getRow(0).getLastCellNum();
  110. sheetAt.shiftRows(0, 1, 1);
  111. XSSFRow row = sheetAt.createRow(0);
  112. XSSFCell cell = row.createCell(0);
  113. //样式设置
  114. CellStyle style = workbook2.createCellStyle();
  115. style.setAlignment(HorizontalAlignment.LEFT);
  116. style.setVerticalAlignment(VerticalAlignment.TOP);
  117. style.setWrapText(true);
  118. cell.setCellStyle(style);
  119. //行高设置
  120. row.setHeightInPoints(54);
  121. Font font = workbook2.createFont();
  122. font.setColor(IndexedColors.BLACK.getIndex());
  123. font.setBold(true);
  124. XSSFRichTextString textString = new XSSFRichTextString("填写说明:\n" +
  125. "(1)翻译标记命名规则:只能输入字母、数字、点、横线和下划线,且以字母开头;\n" +
  126. "(2)翻译标记全局唯一,不可重复;\n" +
  127. "(3)翻译语言必须填写一项;");
  128. textString.applyFont(0, 5, font);
  129. cell.setCellValue(textString);
  130. //合并单元格
  131. sheetAt.addMergedRegionUnsafe(new CellRangeAddress(0, 0, 0, lastCellNum - 1));
  132. //冻结行下移
  133. sheetAt.createFreezePane(0, 2);
  134. //校验规则下移
  135. List<XSSFDataValidation> dataValidations = sheetAt.getDataValidations();
  136. List<DataValidation> dvNew = new ArrayList<>();
  137. for (DataValidation dataValidation : dataValidations) {
  138. DataValidationConstraint constraint = dataValidation.getValidationConstraint();
  139. CellRangeAddressList regions = dataValidation.getRegions();
  140. CellRangeAddress crd = regions.getCellRangeAddresses()[0];
  141. CellRangeAddressList cellRangeAddressList = new CellRangeAddressList(crd.getFirstRow() + 1, crd.getLastRow() + 1, crd.getFirstColumn(), crd.getLastColumn());
  142. DataValidationHelper helper = sheetAt.getDataValidationHelper();
  143. dvNew.add(helper.createValidation(constraint, cellRangeAddressList));
  144. }
  145. sheetAt.getCTWorksheet().unsetDataValidations();
  146. for (DataValidation item : dvNew) {
  147. sheetAt.addValidationData(item);
  148. }
  149. multipartFile = ExcelUtil.workbookToCommonsMultipartFile(workbook2, fileName);
  150. }
  151. return multipartFile;
  152. }
  153. public static List<ExcelExportEntity> getImportExcelExportEntityList(boolean isError, Map<String, String> keyMap) {
  154. List<ExcelExportEntity> entitys = new ArrayList<>();
  155. if (isError) {
  156. entitys.add(new ExcelExportEntity("异常原因(errorsInfo)", "errorsInfo"));
  157. }
  158. for (String key : keyMap.keySet()) {
  159. String name = keyMap.get(key);
  160. entitys.add(new ExcelExportEntity(name + "(" + key + ")", key));
  161. }
  162. return entitys;
  163. }
  164. /**
  165. * 导出表格方法
  166. *
  167. * @param temporaryFilePath
  168. * @param sheetName excel名称
  169. * @param keyMap 字段key-name
  170. * @param list 数据
  171. * @param excelModel 表格参数
  172. * @return
  173. */
  174. public static DownloadVO creatModelExcel(String temporaryFilePath, String sheetName, Map<String, String> keyMap, List<Map<String, Object>> list, ExcelModel excelModel) {
  175. List<String> keys = excelModel.getSelectKey();
  176. DownloadVO vo = DownloadVO.builder().build();
  177. List<ExcelExportEntity> entitys = new ArrayList<>();
  178. for (String key : keys) {
  179. String name = keyMap.get(key);
  180. entitys.add(new ExcelExportEntity(name, key));
  181. }
  182. ExportParams exportParams = new ExportParams(null, "表单信息");
  183. exportParams.setStyle(ExcelExportStyler.class);
  184. exportParams.setType(ExcelType.XSSF);
  185. try {
  186. @Cleanup Workbook workbook = new HSSFWorkbook();
  187. if (entitys.size() > 0) {
  188. //去除空数据
  189. List<Map<String, Object>> dataList = new ArrayList<>();
  190. for (Map<String, Object> map : list) {
  191. int i = 0;
  192. for (String key : keys) {
  193. Object o = map.get(key);
  194. if (o != null) {
  195. i++;
  196. }
  197. }
  198. if (i > 0) {
  199. dataList.add(map);
  200. }
  201. }
  202. if (dataList.size() == 0) {
  203. dataList.add(new HashMap<>());
  204. }
  205. workbook = ExcelExportUtil.exportExcel(exportParams, entitys, dataList);
  206. ExcelHelper helper = new ExcelHelper();
  207. helper.init(workbook, exportParams, entitys, excelModel);
  208. helper.doPreHandle();
  209. helper.doPostHandle();
  210. }
  211. String fileName = sheetName + "_" + DateUtil.dateNow("yyyyMMddHHmmss") + ".xls";
  212. MultipartFile multipartFile = ExcelUtil.workbookToCommonsMultipartFile(workbook, fileName);
  213. FileInfo fileInfo = FileUploadUtils.uploadFile(new FileParameter(temporaryFilePath, fileName), multipartFile);
  214. vo.setName(fileInfo.getFilename());
  215. vo.setUrl(UploaderUtil.uploaderFile(fileInfo.getFilename() + "#" + "Temporary") + "&name=" + fileName);
  216. } catch (Exception e) {
  217. e.printStackTrace();
  218. }
  219. return vo;
  220. }
  221. public static DownloadVO exportExceptionReport(String temporaryFilePath, String menuFullName, Map<String, String> keyMap, List<Map<String, Object>> dataList, ExcelModel excelModel) {
  222. DownloadVO vo = DownloadVO.builder().build();
  223. try {
  224. List<ExcelExportEntity> entitys = ExcelTool.getImportExcelExportEntityList(true, keyMap);
  225. @Cleanup Workbook workbook = new HSSFWorkbook();
  226. ExportParams exportParams = new ExportParams(null, "错误报告");
  227. exportParams.setFreezeCol(1);
  228. exportParams.setType(ExcelType.XSSF);
  229. exportParams.setStyle(ExcelExportStyler.class);
  230. workbook = ExcelExportUtil.exportExcel(exportParams, entitys, dataList);
  231. ExcelHelper helper = new ExcelHelper();
  232. helper.init(workbook, exportParams, entitys, excelModel);
  233. helper.doPreHandle();
  234. helper.doPostHandle();
  235. String fileName = menuFullName + "导入模板错误报告_" + DateUtil.dateNow("yyyyMMddHHmmss") + ".xls";
  236. MultipartFile multipartFile = ExcelUtil.workbookToCommonsMultipartFile(workbook, fileName);
  237. FileInfo fileInfo = FileUploadUtils.uploadFile(new FileParameter(temporaryFilePath, fileName), multipartFile);
  238. vo.setName(fileInfo.getFilename());
  239. vo.setUrl(UploaderUtil.uploaderFile(fileInfo.getFilename() + "#" + "Temporary") + "&name=" + fileName);
  240. } catch (Exception e) {
  241. e.printStackTrace();
  242. }
  243. return vo;
  244. }
  245. public static Map<String, Object> importPreview(String temporaryFilePath, String fileName, Map<String, String> keyMap) {
  246. return importPreview(temporaryFilePath, fileName, keyMap, 0, 1);
  247. }
  248. public static Map<String, Object> importPreview(String temporaryFilePath, String fileName, Map<String, String> keyMap, Integer titleIndex, Integer headerRows) {
  249. Map<String, Object> headAndDataMap = new HashMap<>(2);
  250. File temporary = FileUploadUtils.downloadFileToLocal(new FileParameter(temporaryFilePath, fileName));
  251. ImportParams params = new ImportParams();
  252. params.setTitleRows(titleIndex);
  253. params.setHeadRows(headerRows);
  254. params.setNeedVerify(true);
  255. List<ExcelViewFieldModel> columns = new ArrayList<>();
  256. for (String key : keyMap.keySet()) {
  257. columns.add(new ExcelViewFieldModel(key, keyMap.get(key)));
  258. }
  259. List<Map<String, Object>> jsonToList;
  260. List<Map> excelDataList;
  261. try {
  262. jsonToList = JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(columns));
  263. InputStream inputStream = ExcelUtil.solveOrginTitle(temporary, titleIndex, headerRows);
  264. excelDataList = ExcelUtil.importExcelByInputStream(inputStream, titleIndex, headerRows, Map.class);
  265. } catch (Exception e) {
  266. e.printStackTrace();
  267. throw new DataException(MsgCode.VS407.get());
  268. }
  269. List<Map<String, Object>> resultList = getResultList(excelDataList, new ArrayList<>(keyMap.keySet()));
  270. if (resultList.size() > 1000) {
  271. throw new DataException(MsgCode.ETD117.get());
  272. }
  273. headAndDataMap.put("dataRow", resultList);
  274. headAndDataMap.put("headerRow", jsonToList);
  275. return headAndDataMap;
  276. }
  277. /**
  278. * key字段处理
  279. *
  280. * @param excelDataList
  281. * @param selectKey
  282. * @return
  283. */
  284. public static List<Map<String, Object>> getResultList(List<Map> excelDataList, List<String> selectKey) {
  285. List<Map<String, Object>> allDataList = new ArrayList<>();
  286. for (int z = 0; z < excelDataList.size(); z++) {
  287. Map<String, Object> dataMap = new HashMap<>(16);
  288. Map m = excelDataList.get(z);
  289. List excelEntrySet = new ArrayList<>(m.entrySet());
  290. //取出的数据最后一行 不带行标签
  291. int resultsize = z == excelDataList.size() - 1 ? excelEntrySet.size() : m.containsKey("excelRowNum") ? excelEntrySet.size() - 1 : excelEntrySet.size();
  292. if (resultsize < selectKey.size()) {
  293. throw new DataException(MsgCode.VS407.get());
  294. }
  295. for (int e = 0; e < resultsize; e++) {
  296. Map.Entry o = (Map.Entry) excelEntrySet.get(e);
  297. String entryKey = o.getKey().toString();
  298. String substring = entryKey.substring(entryKey.lastIndexOf("(") + 1, entryKey.lastIndexOf(")"));
  299. boolean contains = selectKey.contains(substring);
  300. if (!contains) {
  301. throw new DataException(MsgCode.VS407.get());
  302. }
  303. dataMap.put(substring, o.getValue());
  304. }
  305. allDataList.add(dataMap);
  306. }
  307. return allDataList;
  308. }
  309. }