ExcelUtil.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. package com.simuwang.base.common.util;
  2. import cn.hutool.core.collection.CollUtil;
  3. import cn.hutool.core.date.DateUtil;
  4. import cn.hutool.core.util.StrUtil;
  5. import com.simuwang.base.common.conts.DateConst;
  6. import org.apache.poi.hssf.usermodel.*;
  7. import org.apache.poi.ss.usermodel.*;
  8. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  9. import org.jsoup.nodes.Element;
  10. import org.jsoup.select.Elements;
  11. import org.slf4j.Logger;
  12. import org.slf4j.LoggerFactory;
  13. import java.io.*;
  14. import java.text.NumberFormat;
  15. import java.util.Date;
  16. import java.util.List;
  17. import java.util.Map;
  18. import org.apache.commons.compress.archivers.ArchiveEntry;
  19. import org.apache.commons.compress.archivers.ArchiveInputStream;
  20. import org.apache.commons.compress.archivers.ArchiveStreamFactory;
  21. import org.apache.commons.compress.utils.IOUtils;
  22. public class ExcelUtil {
  23. private static final Logger logger = LoggerFactory.getLogger(ExcelUtil.class);
  24. public static boolean isExcel(String fileName) {
  25. return StrUtil.isNotBlank(fileName) && (fileName.endsWith("xls") || fileName.endsWith("xlsx") || fileName.endsWith("XLS") || fileName.endsWith("XLSX"));
  26. }
  27. public static boolean isPdf(String fileName) {
  28. return StrUtil.isNotBlank(fileName) && (fileName.endsWith("pdf") || fileName.endsWith("PDF"));
  29. }
  30. public static boolean isZip(String fileName) {
  31. return StrUtil.isNotBlank(fileName) && (fileName.endsWith("zip") || fileName.endsWith("ZIP"));
  32. }
  33. public static boolean isHTML(String fileName) {
  34. return StrUtil.isNotBlank(fileName) && fileName.endsWith("html");
  35. }
  36. public static Sheet getSheet(File file, int sheetIndex) {
  37. if (file == null || !file.exists()) {
  38. return null;
  39. }
  40. InputStream is = file2InStream(file);
  41. String[] arr = file.getName().split("\\.");
  42. String ext = arr[arr.length - 1];
  43. Sheet sheet = null;
  44. try {
  45. sheet = getSheet(is, ext, sheetIndex);
  46. } catch (Exception e) {
  47. logger.error(e.getMessage());
  48. if (e.getMessage().contains("XSSF instead of HSSF")) {
  49. is = file2InStream(file);
  50. try {
  51. sheet = getSheet(is, "xlsx", sheetIndex);
  52. } catch (IOException e1) {
  53. e1.printStackTrace();
  54. }
  55. } else if (e.getMessage().contains("HSSF instead of XSSF")) {
  56. is = file2InStream(file);
  57. try {
  58. sheet = getSheet(is, "xls", sheetIndex);
  59. } catch (IOException e1) {
  60. e1.printStackTrace();
  61. }
  62. } else if ("xls".equals(ext) && e.getMessage().contains("left 4 bytes remaining still to be read")) {
  63. file = changeXls(file);
  64. is = file2InStream(file);
  65. try {
  66. sheet = getSheet(is, "xls", sheetIndex);
  67. logger.info("文件转换成功!");
  68. } catch (IOException e1) {
  69. e1.printStackTrace();
  70. }
  71. } else {
  72. sheet = null;
  73. }
  74. }
  75. return sheet;
  76. }
  77. public static Sheet getSheet(InputStream is, String ext, int sheetIndex) throws IOException {
  78. if (ext == null) {
  79. ext = "xls";
  80. }
  81. ext = ext.toLowerCase();
  82. Sheet sheet = null;
  83. if ("xls".equals(ext)) {
  84. Workbook wb = new HSSFWorkbook(is);
  85. sheet = getSheet(wb, sheetIndex, null);
  86. } else if ("xlsx".equals(ext)) {
  87. Workbook wb = new XSSFWorkbook(is);
  88. sheet = getSheet(wb, sheetIndex, null);
  89. }
  90. return sheet;
  91. }
  92. private static Sheet getSheet(Workbook wb, int sheetIndex, String sheetName) throws IOException {
  93. if (wb != null) {
  94. Sheet sheet = null;
  95. if (sheetIndex > -1) {
  96. sheet = wb.getSheetAt(sheetIndex);
  97. } else if (StrUtil.isNotBlank(sheetName) && !"null".equals(sheetName.toLowerCase())) {
  98. sheet = wb.getSheet(sheetName);
  99. }
  100. wb.close();
  101. // 同时会把文件输入流关闭
  102. return sheet;
  103. }
  104. return null;
  105. }
  106. public static InputStream file2InStream(File file) {
  107. if (!file.exists()) {
  108. return null;
  109. } else {
  110. FileInputStream is = null;
  111. try {
  112. is = new FileInputStream(file);
  113. } catch (FileNotFoundException var3) {
  114. var3.printStackTrace();
  115. }
  116. return is;
  117. }
  118. }
  119. public static File changeXls(File file) {
  120. try {
  121. jxl.Workbook workbook = jxl.Workbook.getWorkbook(file);
  122. String fileName = "copy-" + file.getName();
  123. File file2 = new File(file.getParent() + "/" + fileName);
  124. if (file2.exists()) {
  125. return file2;
  126. }
  127. jxl.write.WritableWorkbook wwb = jxl.Workbook.createWorkbook(file2, workbook);
  128. wwb.write();
  129. wwb.close();
  130. workbook.close();
  131. return file2;
  132. } catch (Exception e) {
  133. e.printStackTrace();
  134. return null;
  135. }
  136. }
  137. public static String getCellValue(Cell cell) {
  138. if (cell == null) {
  139. return null;
  140. }
  141. String cellValue = "";
  142. switch (cell.getCellTypeEnum()) {
  143. case STRING:
  144. cellValue = cell.getStringCellValue();
  145. break;
  146. case NUMERIC:
  147. if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
  148. // 如果是日期格式的数字
  149. Date dateCellValue = cell.getDateCellValue();
  150. cellValue = DateUtil.format(dateCellValue, DateConst.YYYY_MM_DD);
  151. } else {
  152. // 否则是纯数字
  153. NumberFormat numberFormat = NumberFormat.getNumberInstance();
  154. numberFormat.setMaximumFractionDigits(15);
  155. double formulaResult = cell.getNumericCellValue();
  156. cellValue = numberFormat.format(formulaResult).replaceAll(",", "");
  157. }
  158. break;
  159. case BOOLEAN:
  160. cellValue = String.valueOf(cell.getBooleanCellValue());
  161. break;
  162. case FORMULA:
  163. // 处理公式结果
  164. try {
  165. cellValue = String.valueOf(cell.getNumericCellValue());
  166. } catch (IllegalStateException e) {
  167. cellValue = cell.getStringCellValue();
  168. }
  169. break;
  170. case BLANK:
  171. break;
  172. case ERROR:
  173. cellValue = "ERROR: " + cell.getErrorCellValue();
  174. break;
  175. default:
  176. cellValue = "";
  177. break;
  178. }
  179. // 去掉换行符号
  180. cellValue = StrUtil.isNotBlank(cellValue) ? cellValue.replaceAll("[\\r\\n]+", "") : "";
  181. return cellValue;
  182. }
  183. public static List<String> extractCompressedFiles(String zipFilePath, String destFilePath) {
  184. List<String> filePathList = CollUtil.newArrayList();
  185. File destFile = new File(destFilePath);
  186. if (!destFile.exists()) {
  187. destFile.mkdirs();
  188. }
  189. try (BufferedInputStream fis = new BufferedInputStream(new FileInputStream(zipFilePath));
  190. ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(fis)) {
  191. ArchiveEntry entry;
  192. while ((entry = ais.getNextEntry()) != null) {
  193. File entryFile = new File(destFilePath, entry.getName());
  194. if (entry.isDirectory()) {
  195. entryFile.mkdirs();
  196. } else {
  197. try (FileOutputStream fos = new FileOutputStream(entryFile)) {
  198. IOUtils.copy(ais, fos);
  199. filePathList.add(entryFile.getPath());
  200. }
  201. }
  202. }
  203. } catch (Exception e) {
  204. e.printStackTrace();
  205. }
  206. return filePathList;
  207. }
  208. public static void writeDataToSheet(Sheet sheet, Elements rows) {
  209. int rowSize = rows.size();
  210. for (int rowNum = 0; rowNum < rowSize; rowNum++) {
  211. Row sheetRow = sheet.createRow(rowNum);
  212. Element elementRow = rows.get(rowNum);
  213. Elements cells = elementRow.select("td");
  214. if (cells.size() == 0) {
  215. cells = elementRow.select("th");
  216. }
  217. int cellSize = cells.size();
  218. for (int cellNum = 0; cellNum < cellSize; cellNum++) {
  219. Cell sheetRowCell = sheetRow.createCell(cellNum);
  220. sheetRowCell.setCellValue(cells.get(cellNum).text());
  221. }
  222. }
  223. }
  224. /**
  225. * 获取优先级高的字段值
  226. *
  227. * @param sheetRow 行
  228. * @param priorityPosition 字段位置
  229. * @param basePosition 优先级搞的字段位置
  230. * @return 优先级高的字段值
  231. */
  232. public static String getPriorityFieldValue(Row sheetRow, Integer priorityPosition, Integer basePosition) {
  233. boolean hasPriorityValue = priorityPosition != null && sheetRow.getCell(priorityPosition) != null && StrUtil.isNotBlank(ExcelUtil.getCellValue(sheetRow.getCell(priorityPosition)));
  234. if (hasPriorityValue) {
  235. return ExcelUtil.getCellValue(sheetRow.getCell(priorityPosition));
  236. }
  237. return basePosition != null && sheetRow.getCell(basePosition) != null ? ExcelUtil.getCellValue(sheetRow.getCell(basePosition)) : null;
  238. }
  239. /**
  240. * 去掉逗号
  241. *
  242. * @param numberData 数字型字符串
  243. * @return 无逗号的数字型字符串
  244. */
  245. public static String numberDataStripCommas(String numberData) {
  246. if (StrUtil.isBlank(numberData)) {
  247. return null;
  248. }
  249. // pdf解析到的值带有",",比如:"10,656,097.37"
  250. String data = numberData.replaceAll(",", "");
  251. if (!StringUtil.isNumeric(data)) {
  252. return null;
  253. }
  254. return data;
  255. }
  256. public static HSSFWorkbook getHSSFWorkbook(String sheetName, List<String> title, Map<String, List<List<String>>> valueMap, HSSFWorkbook wb) {
  257. // 第一步,创建一个HSSFWorkbook,对应一个Excel文件
  258. if (wb == null) {
  259. wb = new HSSFWorkbook();
  260. }
  261. try {
  262. // 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
  263. HSSFSheet sheet = wb.createSheet(sheetName);
  264. // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
  265. HSSFRow row = sheet.createRow(0);
  266. // 第四步,创建单元格,并设置值表头 设置表头居中
  267. HSSFCellStyle style = wb.createCellStyle();
  268. style.setAlignment(HorizontalAlignment.LEFT);
  269. style.setWrapText(true);
  270. sheet.setColumnWidth(0, 10000);
  271. sheet.setColumnWidth(1, 10000);
  272. sheet.setColumnWidth(2, 5000);
  273. sheet.setColumnWidth(3, 8000);
  274. sheet.setColumnWidth(4, 8000);
  275. sheet.setColumnWidth(5, 5000);
  276. //声明列对象
  277. HSSFCell cell = null;
  278. //创建标题
  279. for (int i = 0; i < title.size(); i++) {
  280. cell = row.createCell(i);
  281. cell.setCellValue(title.get(i));
  282. cell.setCellStyle(style);
  283. }
  284. List<List<String>> values = valueMap.get(sheetName);
  285. //创建内容
  286. for (int i = 0; i < values.size(); i++) {
  287. row = sheet.createRow(i + 1);
  288. for (int j = 0; j < values.get(i).size(); j++) {
  289. //将内容按顺序赋给对应的列对象
  290. row.createCell(j).setCellValue(values.get(i).get(j));
  291. }
  292. }
  293. } catch (Exception e) {
  294. logger.error(e.getMessage(), e);
  295. }
  296. return wb;
  297. }
  298. }