ExcelUtil.java 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. package com.simuwang.base.common.util;
  2. import cn.hutool.core.collection.CollUtil;
  3. import cn.hutool.core.util.StrUtil;
  4. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  5. import org.apache.poi.ss.usermodel.Cell;
  6. import org.apache.poi.ss.usermodel.Sheet;
  7. import org.apache.poi.ss.usermodel.Workbook;
  8. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  9. import org.slf4j.Logger;
  10. import org.slf4j.LoggerFactory;
  11. import java.io.*;
  12. import java.text.NumberFormat;
  13. import java.util.List;
  14. import org.apache.commons.compress.archivers.ArchiveEntry;
  15. import org.apache.commons.compress.archivers.ArchiveInputStream;
  16. import org.apache.commons.compress.archivers.ArchiveStreamFactory;
  17. import org.apache.commons.compress.utils.IOUtils;
  18. public class ExcelUtil {
  19. private static final Logger logger = LoggerFactory.getLogger(ExcelUtil.class);
  20. public static boolean isExcel(String name) {
  21. return name.endsWith("xls") || name.endsWith("xlsx");
  22. }
  23. public static boolean isPdf(String name) {
  24. return name.endsWith("pdf") || name.endsWith("PDF");
  25. }
  26. public static boolean isZip(String filePath) {
  27. return filePath.endsWith("zip") || filePath.endsWith("ZIP") || filePath.endsWith("rar") || filePath.endsWith("RAR");
  28. }
  29. public static Sheet getSheet(File file, int sheetIndex) {
  30. if (file == null || !file.exists()) {
  31. return null;
  32. }
  33. InputStream is = file2InStream(file);
  34. String[] arr = file.getName().split("\\.");
  35. String ext = arr[arr.length - 1];
  36. Sheet sheet = null;
  37. try {
  38. sheet = getSheet(is, ext, sheetIndex);
  39. } catch (Exception e) {
  40. logger.error(e.getMessage());
  41. if (e.getMessage().contains("XSSF instead of HSSF")) {
  42. is = file2InStream(file);
  43. try {
  44. sheet = getSheet(is, "xlsx", sheetIndex);
  45. } catch (IOException e1) {
  46. e1.printStackTrace();
  47. }
  48. } else if (e.getMessage().contains("HSSF instead of XSSF")) {
  49. is = file2InStream(file);
  50. try {
  51. sheet = getSheet(is, "xls", sheetIndex);
  52. } catch (IOException e1) {
  53. e1.printStackTrace();
  54. }
  55. } else if ("xls".equals(ext) && e.getMessage().contains("left 4 bytes remaining still to be read")) {
  56. file = changeXls(file);
  57. is = file2InStream(file);
  58. try {
  59. sheet = getSheet(is, "xls", sheetIndex);
  60. logger.info("文件转换成功!");
  61. } catch (IOException e1) {
  62. e1.printStackTrace();
  63. }
  64. } else {
  65. sheet = null;
  66. }
  67. }
  68. return sheet;
  69. }
  70. public static Sheet getSheet(InputStream is, String ext, int sheetIndex) throws IOException {
  71. if (ext == null) {
  72. ext = "xls";
  73. }
  74. ext = ext.toLowerCase();
  75. Sheet sheet = null;
  76. if ("xls".equals(ext)) {
  77. Workbook wb = new HSSFWorkbook(is);
  78. sheet = getSheet(wb, sheetIndex, null);
  79. } else if ("xlsx".equals(ext)) {
  80. Workbook wb = new XSSFWorkbook(is);
  81. sheet = getSheet(wb, sheetIndex, null);
  82. }
  83. return sheet;
  84. }
  85. private static Sheet getSheet(Workbook wb, int sheetIndex, String sheetName) throws IOException {
  86. if (wb != null) {
  87. Sheet sheet = null;
  88. if (sheetIndex > -1) {
  89. sheet = wb.getSheetAt(sheetIndex);
  90. } else if (StrUtil.isNotBlank(sheetName) && !"null".equals(sheetName.toLowerCase())) {
  91. sheet = wb.getSheet(sheetName);
  92. }
  93. wb.close();
  94. // 同时会把文件输入流关闭
  95. return sheet;
  96. }
  97. return null;
  98. }
  99. public static InputStream file2InStream(File file) {
  100. if (!file.exists()) {
  101. return null;
  102. } else {
  103. FileInputStream is = null;
  104. try {
  105. is = new FileInputStream(file);
  106. } catch (FileNotFoundException var3) {
  107. var3.printStackTrace();
  108. }
  109. return is;
  110. }
  111. }
  112. public static File changeXls(File file) {
  113. try {
  114. jxl.Workbook workbook = jxl.Workbook.getWorkbook(file);
  115. String fileName = "copy-" + file.getName();
  116. File file2 = new File(file.getParent() + "/" + fileName);
  117. if (file2.exists()) {
  118. return file2;
  119. }
  120. jxl.write.WritableWorkbook wwb = jxl.Workbook.createWorkbook(file2, workbook);
  121. wwb.write();
  122. wwb.close();
  123. workbook.close();
  124. return file2;
  125. } catch (Exception e) {
  126. e.printStackTrace();
  127. return null;
  128. }
  129. }
  130. public static String getCellValue(Cell cell) {
  131. if (cell == null) {
  132. return null;
  133. }
  134. String cellValue = "";
  135. switch (cell.getCellTypeEnum()) {
  136. case STRING:
  137. cellValue = cell.getStringCellValue();
  138. break;
  139. case NUMERIC:
  140. if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
  141. // 如果是日期格式的数字
  142. cellValue = cell.getDateCellValue().toString();
  143. } else {
  144. // 否则是纯数字
  145. NumberFormat numberFormat = NumberFormat.getNumberInstance();
  146. numberFormat.setMaximumFractionDigits(15);
  147. double formulaResult = cell.getNumericCellValue();
  148. cellValue = numberFormat.format(formulaResult).replaceAll(",", "");
  149. }
  150. break;
  151. case BOOLEAN:
  152. cellValue = String.valueOf(cell.getBooleanCellValue());
  153. break;
  154. case FORMULA:
  155. // 处理公式结果
  156. try {
  157. cellValue = String.valueOf(cell.getNumericCellValue());
  158. } catch (IllegalStateException e) {
  159. cellValue = cell.getStringCellValue();
  160. }
  161. break;
  162. case BLANK:
  163. break;
  164. case ERROR:
  165. cellValue = "ERROR: " + cell.getErrorCellValue();
  166. break;
  167. default:
  168. cellValue = "";
  169. break;
  170. }
  171. // 去掉换行符号
  172. cellValue = StrUtil.isNotBlank(cellValue) ? cellValue.replaceAll("[\\r\\n]+", "") : "";
  173. return cellValue;
  174. }
  175. public static List<String> extractCompressedFiles(String zipFilePath, String destFilePath) {
  176. List<String> filePathList = CollUtil.newArrayList();
  177. File destFile = new File(destFilePath);
  178. if (!destFile.exists()) {
  179. destFile.mkdirs();
  180. }
  181. try (BufferedInputStream fis = new BufferedInputStream(new FileInputStream(zipFilePath));
  182. ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(fis)) {
  183. ArchiveEntry entry;
  184. while ((entry = ais.getNextEntry()) != null) {
  185. File entryFile = new File(destFilePath, entry.getName());
  186. if (entry.isDirectory()) {
  187. entryFile.mkdirs();
  188. } else {
  189. try (FileOutputStream fos = new FileOutputStream(entryFile)) {
  190. IOUtils.copy(ais, fos);
  191. filePathList.add(entryFile.getAbsolutePath());
  192. }
  193. }
  194. }
  195. } catch (Exception e) {
  196. e.printStackTrace();
  197. }
  198. return filePathList;
  199. }
  200. }