ExcelUtil.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. package jnpf.util;
  2. import cn.afterturn.easypoi.excel.ExcelImportUtil;
  3. import cn.afterturn.easypoi.excel.entity.ImportParams;
  4. import jakarta.servlet.http.HttpServletResponse;
  5. import jnpf.exception.ImportException;
  6. import jnpf.support.MyStandardMultipartFile;
  7. import lombok.Cleanup;
  8. import org.apache.catalina.core.ApplicationPart;
  9. import org.apache.commons.collections4.CollectionUtils;
  10. import org.apache.commons.lang3.StringUtils;
  11. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  12. import org.apache.poi.ss.usermodel.*;
  13. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  14. import org.apache.tomcat.util.http.fileupload.FileItem;
  15. import org.apache.tomcat.util.http.fileupload.FileItemFactory;
  16. import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
  17. import org.springframework.web.multipart.MultipartFile;
  18. import java.io.*;
  19. import java.net.URLEncoder;
  20. import java.util.*;
  21. import java.util.regex.Matcher;
  22. import java.util.regex.Pattern;
  23. /**
  24. * @author JNPF开发平台组
  25. * @version V3.1.0
  26. * @copyright 引迈信息技术有限公司
  27. * @date 2021/3/16 10:51
  28. */
  29. public class ExcelUtil {
  30. /**
  31. * Workbook 转 MultipartFile
  32. *
  33. * @param workbook excel文档
  34. * @param fileName 文件名
  35. * @return
  36. */
  37. public static MultipartFile workbookToCommonsMultipartFile(Workbook workbook, String fileName) {
  38. //Workbook转FileItem
  39. FileItemFactory factory = new DiskFileItemFactory(16, null);
  40. FileItem fileItem = factory.createItem("textField", "text/plain", true, fileName);
  41. try {
  42. OutputStream os = fileItem.getOutputStream();
  43. workbook.write(os);
  44. os.close();
  45. //FileItem转MultipartFile
  46. MultipartFile multipartFile = new MyStandardMultipartFile(new ApplicationPart(fileItem, null), fileName);
  47. return multipartFile;
  48. } catch (Exception e) {
  49. e.printStackTrace();
  50. }
  51. return null;
  52. }
  53. /**
  54. * 下载excel
  55. *
  56. * @param fileName excel名称
  57. * @param workbook
  58. */
  59. public static void dowloadExcel(Workbook workbook, String fileName) {
  60. try {
  61. HttpServletResponse response = ServletUtil.getResponse();
  62. response.setCharacterEncoding("UTF-8");
  63. response.setHeader("content-Type", "application/vnd.ms-excel");
  64. response.setHeader("Content-Disposition",
  65. "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
  66. workbook.write(response.getOutputStream());
  67. } catch (IOException e) {
  68. e.printStackTrace();
  69. }
  70. }
  71. /**
  72. * excel转成实体
  73. *
  74. * @param filePath 路径
  75. * @param titleRows 行
  76. * @param headerRows 列
  77. * @param pojoClass 实体
  78. * @param <T>
  79. * @return
  80. */
  81. public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
  82. if (StringUtils.isBlank(filePath)) {
  83. return null;
  84. }
  85. ImportParams params = new ImportParams();
  86. params.setTitleRows(titleRows);
  87. params.setHeadRows(headerRows);
  88. List<T> list = null;
  89. try {
  90. list = ExcelImportUtil.importExcel(new File(jnpf.util.XSSEscape.escapePath(filePath)), pojoClass, params);
  91. } catch (Exception e) {
  92. e.printStackTrace();
  93. }
  94. return list;
  95. }
  96. /**
  97. * excel转成实体
  98. *
  99. * @param file 文件
  100. * @param titleRows 行
  101. * @param headerRows 列
  102. * @param pojoClass 实体
  103. * @param <T>
  104. * @return
  105. */
  106. public static <T> List<T> importExcel(File file, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws ImportException {
  107. if (file == null) {
  108. return null;
  109. }
  110. ImportParams params = new ImportParams();
  111. params.setTitleRows(titleRows);
  112. params.setHeadRows(headerRows);
  113. List<T> list = null;
  114. try {
  115. list = ExcelImportUtil.importExcel(file, pojoClass, params);
  116. } catch (Exception e) {
  117. throw new ImportException(e.getMessage());
  118. }
  119. return list;
  120. }
  121. /**
  122. * excel转成实体
  123. *
  124. * @param inputStream 文件流
  125. * @param titleRows 行
  126. * @param headerRows 列
  127. * @param pojoClass 实体
  128. * @param <T>
  129. * @return
  130. */
  131. public static <T> List<T> importExcelByInputStream(InputStream inputStream, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws Exception {
  132. if (inputStream == null) {
  133. return null;
  134. }
  135. ImportParams params = new ImportParams();
  136. params.setTitleRows(titleRows);
  137. params.setHeadRows(headerRows);
  138. List<T> list = null;
  139. list = ExcelImportUtil.importExcel(inputStream, pojoClass, params);
  140. return list;
  141. }
  142. /**
  143. * excel转成实体
  144. *
  145. * @param file 文件
  146. * @param titleRows 行
  147. * @param headerRows 列
  148. * @param pojoClass 实体
  149. * @param <T>
  150. * @return
  151. */
  152. public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) {
  153. ImportParams params = new ImportParams();
  154. params.setTitleRows(titleRows);
  155. params.setHeadRows(headerRows);
  156. List<T> list = null;
  157. try {
  158. list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
  159. } catch (Exception e) {
  160. e.printStackTrace();
  161. }
  162. return list;
  163. }
  164. /**
  165. * 备用方案,读取不到时间暂用此方法
  166. * 通过基础poi读取NUMERIC转换成时间格式
  167. *
  168. * @param
  169. * @return
  170. * @copyright 引迈信息技术有限公司
  171. * @date 2023/2/3
  172. */
  173. public static void imoportExcelToMap(File file, Integer titleIndex, List<Map> excelDataList) {
  174. List<Map<String, Object>> mapList = new ArrayList<>();
  175. FileInputStream inputStream = null;
  176. try {
  177. String fileName = file.getName();
  178. @Cleanup Workbook workbook = null;
  179. inputStream = new FileInputStream(file);
  180. try {
  181. workbook = new HSSFWorkbook(inputStream);
  182. } catch (Exception e) {
  183. inputStream = new FileInputStream(file);
  184. workbook = new XSSFWorkbook(inputStream);
  185. }
  186. Sheet sheet = workbook.getSheetAt(0);
  187. Row titleRow = sheet.getRow(titleIndex - 1);
  188. for (int i = titleIndex; i < sheet.getPhysicalNumberOfRows(); i++) {
  189. Row row = sheet.getRow(i);
  190. Map<String, Object> map = new HashMap<>();
  191. for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {
  192. Cell cell = row.getCell(j);
  193. Cell titleCell = titleRow.getCell(j);
  194. if (cell != null && org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
  195. short format = cell.getCellStyle().getDataFormat();
  196. if (cell.getDateCellValue() != null && format > 0) {
  197. //表头数据
  198. String titleName = titleCell.getStringCellValue();
  199. if (StringUtil.isEmpty(titleName)) {
  200. titleName = sheet.getRow(titleIndex - 2).getCell(j).getStringCellValue();
  201. }
  202. //单元格内容
  203. Date dateCellValue = cell.getDateCellValue();
  204. String valueName = DateUtil.daFormat(dateCellValue);
  205. map.put(titleName, valueName);
  206. }
  207. }
  208. }
  209. mapList.add(map);
  210. }
  211. //基础poi读取到时间同步到easypoi读取到的数据中去
  212. if (!CollectionUtils.sizeIsEmpty(mapList)) {
  213. for (int n = 0; n < mapList.size(); n++) {
  214. Map<String, Object> a = mapList.get(n);
  215. Map b = excelDataList.get(n);
  216. if (a != null) {
  217. for (String key : a.keySet()) {
  218. if (b.containsKey(key)) b.put(key, a.get(key));
  219. }
  220. }
  221. }
  222. }
  223. } catch (Exception e) {
  224. e.printStackTrace();
  225. } finally {
  226. try {
  227. inputStream.close();
  228. } catch (IOException e) {
  229. e.printStackTrace();
  230. }
  231. }
  232. }
  233. public static InputStream solveOrginTitle(File file, Integer rowLen) throws IOException {
  234. return solveOrginTitle(file, 0, rowLen);
  235. }
  236. public static InputStream solveOrginTitle(File file, Integer titleIndex, Integer rowLen) throws IOException {
  237. @Cleanup Workbook workbook = WorkbookFactory.create(file);
  238. Sheet sheet = workbook.getSheetAt(0);
  239. for (int i = titleIndex; i < titleIndex + rowLen; i++) {
  240. Row headerRow = sheet.getRow(i);
  241. int lastCellNum = headerRow.getLastCellNum();
  242. for (int j = 0; j < lastCellNum; j++) {
  243. Cell cell = headerRow.getCell(j);
  244. if (cell == null) {
  245. continue;
  246. }
  247. String name = cell.getStringCellValue();
  248. Comment cellComment = cell.getCellComment();
  249. //都没有标题就跳过
  250. if (StringUtils.isEmpty(name) && cellComment == null) {
  251. continue;
  252. }
  253. //有标题没批注,说明表头有问题
  254. if (Objects.isNull(cellComment)) {
  255. throw new RuntimeException();
  256. }
  257. name = name + "(" + cellComment.getString().getString() + ")";
  258. cell.setCellValue(name);
  259. }
  260. }
  261. MultipartFile multipartFile = ExcelUtil.workbookToCommonsMultipartFile(workbook, file.getName());
  262. InputStream inputStream = multipartFile.getInputStream();
  263. return inputStream;
  264. }
  265. /**
  266. * 判断字符串内有没有括号
  267. *
  268. * @param str
  269. * @return
  270. */
  271. public static boolean matcherFind(String str) {
  272. Pattern pattern = Pattern.compile("(.*)\\((.*?)\\)");
  273. Matcher matcher = pattern.matcher(str);
  274. return matcher.find();
  275. }
  276. /**
  277. * 获取标题括号内得id
  278. *
  279. * @param cellValue
  280. * @return
  281. */
  282. public static String getIdFromCellValue(String cellValue) {
  283. String id = "";
  284. if (matcherFind(cellValue)) {
  285. id = cellValue.substring(cellValue.lastIndexOf("(") + 1, cellValue.lastIndexOf(")"));
  286. }
  287. return id;
  288. }
  289. }