ExcelUtil.java 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  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.exceptions.ExceptionUtil;
  5. import cn.hutool.core.lang.Pair;
  6. import cn.hutool.core.util.StrUtil;
  7. import com.github.junrar.Archive;
  8. import com.github.junrar.exception.RarException;
  9. import com.github.junrar.rarfile.FileHeader;
  10. import com.simuwang.base.common.conts.DateConst;
  11. import com.simuwang.base.common.conts.EmailDataDirectionConst;
  12. import com.simuwang.base.pojo.vo.*;
  13. import org.apache.commons.io.FileUtils;
  14. import org.apache.pdfbox.Loader;
  15. import org.apache.pdfbox.pdmodel.PDDocument;
  16. import org.apache.poi.hssf.usermodel.*;
  17. import org.apache.poi.ss.usermodel.*;
  18. import org.apache.poi.ss.util.CellRangeAddress;
  19. import org.apache.poi.xssf.usermodel.*;
  20. import org.jsoup.Jsoup;
  21. import org.jsoup.nodes.Document;
  22. import org.jsoup.nodes.Element;
  23. import org.jsoup.select.Elements;
  24. import org.slf4j.Logger;
  25. import org.slf4j.LoggerFactory;
  26. import java.io.*;
  27. import java.nio.file.Files;
  28. import java.nio.file.Paths;
  29. import java.text.NumberFormat;
  30. import java.time.LocalDate;
  31. import java.time.format.DateTimeFormatter;
  32. import java.util.*;
  33. import org.apache.commons.compress.archivers.ArchiveEntry;
  34. import org.apache.commons.compress.archivers.ArchiveInputStream;
  35. import org.apache.commons.compress.archivers.ArchiveStreamFactory;
  36. import org.apache.commons.compress.utils.IOUtils;
  37. import technology.tabula.ObjectExtractor;
  38. import technology.tabula.Page;
  39. import technology.tabula.PageIterator;
  40. import technology.tabula.RectangularTextContainer;
  41. import technology.tabula.extractors.SpreadsheetExtractionAlgorithm;
  42. public class ExcelUtil {
  43. private static final Logger logger = LoggerFactory.getLogger(ExcelUtil.class);
  44. public static boolean isExcel(String fileName) {
  45. return StrUtil.isNotBlank(fileName) && (fileName.endsWith("xls") || fileName.endsWith("xlsx") || fileName.endsWith("XLS") || fileName.endsWith("XLSX"));
  46. }
  47. public static boolean isPdf(String fileName) {
  48. return StrUtil.isNotBlank(fileName) && (fileName.endsWith("pdf") || fileName.endsWith("PDF"));
  49. }
  50. public static boolean isZip(String fileName) {
  51. return StrUtil.isNotBlank(fileName) && (fileName.endsWith("zip") || fileName.endsWith("ZIP"));
  52. }
  53. public static boolean isHTML(String fileName) {
  54. return StrUtil.isNotBlank(fileName) && fileName.endsWith("html");
  55. }
  56. public static boolean isRAR(String fileName) {
  57. return StrUtil.isNotBlank(fileName) && (fileName.endsWith("rar") || fileName.endsWith("RAR"));
  58. }
  59. public static Sheet getSheet(File file, int sheetIndex) {
  60. if (file == null || !file.exists()) {
  61. return null;
  62. }
  63. InputStream is = file2InStream(file);
  64. String[] arr = file.getName().split("\\.");
  65. String ext = arr[arr.length - 1];
  66. Sheet sheet = null;
  67. try {
  68. sheet = getSheet(is, ext, sheetIndex);
  69. } catch (Exception e) {
  70. logger.error(e.getMessage());
  71. if (e.getMessage().contains("XSSF instead of HSSF")) {
  72. is = file2InStream(file);
  73. try {
  74. sheet = getSheet(is, "xlsx", sheetIndex);
  75. } catch (IOException e1) {
  76. e1.printStackTrace();
  77. }
  78. } else if (e.getMessage().contains("HSSF instead of XSSF")) {
  79. is = file2InStream(file);
  80. try {
  81. sheet = getSheet(is, "xls", sheetIndex);
  82. } catch (IOException e1) {
  83. e1.printStackTrace();
  84. }
  85. } else if ("xls".equals(ext) && e.getMessage().contains("left 4 bytes remaining still to be read")) {
  86. file = changeXls(file);
  87. is = file2InStream(file);
  88. try {
  89. sheet = getSheet(is, "xls", sheetIndex);
  90. logger.info("文件转换成功!");
  91. } catch (IOException e1) {
  92. e1.printStackTrace();
  93. }
  94. } else {
  95. sheet = null;
  96. }
  97. }
  98. return sheet;
  99. }
  100. public static Sheet getSheet(InputStream is, String ext, int sheetIndex) throws IOException {
  101. if (ext == null) {
  102. ext = "xls";
  103. }
  104. ext = ext.toLowerCase();
  105. Sheet sheet = null;
  106. if ("xls".equals(ext)) {
  107. Workbook wb = new HSSFWorkbook(is);
  108. sheet = getSheet(wb, sheetIndex, null);
  109. } else if ("xlsx".equals(ext)) {
  110. Workbook wb = new XSSFWorkbook(is);
  111. sheet = getSheet(wb, sheetIndex, null);
  112. }
  113. return sheet;
  114. }
  115. private static Sheet getSheet(Workbook wb, int sheetIndex, String sheetName) throws IOException {
  116. if (wb != null) {
  117. Sheet sheet = null;
  118. if (sheetIndex > -1) {
  119. sheet = wb.getSheetAt(sheetIndex);
  120. } else if (StrUtil.isNotBlank(sheetName) && !"null".equals(sheetName.toLowerCase())) {
  121. sheet = wb.getSheet(sheetName);
  122. }
  123. wb.close();
  124. // 同时会把文件输入流关闭
  125. return sheet;
  126. }
  127. return null;
  128. }
  129. public static InputStream file2InStream(File file) {
  130. if (!file.exists()) {
  131. return null;
  132. } else {
  133. FileInputStream is = null;
  134. try {
  135. is = new FileInputStream(file);
  136. } catch (FileNotFoundException var3) {
  137. var3.printStackTrace();
  138. }
  139. return is;
  140. }
  141. }
  142. public static File changeXls(File file) {
  143. try {
  144. jxl.Workbook workbook = jxl.Workbook.getWorkbook(file);
  145. String fileName = "copy-" + file.getName();
  146. File file2 = new File(file.getParent() + "/" + fileName);
  147. if (file2.exists()) {
  148. return file2;
  149. }
  150. jxl.write.WritableWorkbook wwb = jxl.Workbook.createWorkbook(file2, workbook);
  151. wwb.write();
  152. wwb.close();
  153. workbook.close();
  154. return file2;
  155. } catch (Exception e) {
  156. e.printStackTrace();
  157. return null;
  158. }
  159. }
  160. public static String getCellValue(Cell cell) {
  161. if (cell == null) {
  162. return null;
  163. }
  164. String cellValue = "";
  165. switch (cell.getCellTypeEnum()) {
  166. case STRING:
  167. cellValue = cell.getStringCellValue();
  168. break;
  169. case NUMERIC:
  170. if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
  171. // 如果是日期格式的数字
  172. Date dateCellValue = cell.getDateCellValue();
  173. cellValue = DateUtil.format(dateCellValue, DateConst.YYYY_MM_DD);
  174. } else {
  175. // 否则是纯数字
  176. NumberFormat numberFormat = NumberFormat.getNumberInstance();
  177. numberFormat.setMaximumFractionDigits(15);
  178. double formulaResult = cell.getNumericCellValue();
  179. cellValue = numberFormat.format(formulaResult).replaceAll(",", "");
  180. }
  181. break;
  182. case BOOLEAN:
  183. cellValue = String.valueOf(cell.getBooleanCellValue());
  184. break;
  185. case FORMULA:
  186. // 处理公式结果
  187. try {
  188. cellValue = String.valueOf(cell.getNumericCellValue());
  189. } catch (IllegalStateException e) {
  190. cellValue = cell.getStringCellValue();
  191. }
  192. break;
  193. case BLANK:
  194. break;
  195. case ERROR:
  196. cellValue = "ERROR: " + cell.getErrorCellValue();
  197. break;
  198. default:
  199. cellValue = "";
  200. break;
  201. }
  202. // 去掉换行符号
  203. cellValue = StrUtil.isNotBlank(cellValue) ? cellValue.replaceAll("[\\r\\n]+", "").replaceAll(",","").trim() : "";
  204. return cellValue;
  205. }
  206. public static List<String> extractCompressedFiles(String filePath, String destFilePath) {
  207. List<String> filePathList = CollUtil.newArrayList();
  208. try {
  209. if(ExcelUtil.isZip(filePath)){
  210. File destFile = new File(destFilePath);
  211. if (!destFile.exists()) {
  212. destFile.mkdirs();
  213. }
  214. logger.info("开始解压zip==================="+filePath);
  215. BufferedInputStream fis = new BufferedInputStream(new FileInputStream(filePath));
  216. ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(fis);
  217. ArchiveEntry entry;
  218. while ((entry = ais.getNextEntry()) != null) {
  219. String uuid = UUID.randomUUID().toString().replaceAll("-","");
  220. String entryName = entry.getName();
  221. String fileName = null;
  222. if(entryName.contains(".")){
  223. fileName = uuid + entryName.substring(entryName.lastIndexOf("."),entryName.length());
  224. }else{
  225. fileName = uuid;
  226. }
  227. File entryFile = new File(destFilePath, fileName);
  228. if (entry.isDirectory()) {
  229. entryFile.mkdirs();
  230. logger.info("解压子文件:{}",entryFile.getName());
  231. } else {
  232. try {
  233. FileOutputStream fos = new FileOutputStream(entryFile);
  234. IOUtils.copy(ais, fos);
  235. filePathList.add(entryFile.getPath());
  236. logger.info("解压子文件:{}",entryFile.getPath());
  237. fos.close();
  238. }catch (Exception e){
  239. logger.error(e.getMessage(),e);
  240. }
  241. }
  242. }
  243. ais.close();
  244. fis.close();
  245. }
  246. if(ExcelUtil.isRAR(filePath)){
  247. logger.info("开始解压RAR==================="+filePath);
  248. String destPath = filePath.replaceAll(".rar", "").replaceAll(".RAR", "");
  249. File destFile = new File(destPath);
  250. if (!destFile.exists()) {
  251. destFile.mkdirs();
  252. }
  253. List<String> rarDir = ExcelUtil.extractRar(filePath, destPath);
  254. for (String subFile : rarDir) {
  255. if(!subFile.contains(destPath)){
  256. subFile = destPath+"/"+subFile;
  257. }
  258. logger.info("解压之后的文件:"+subFile);
  259. }
  260. filePathList.addAll(rarDir);
  261. }
  262. }catch (Exception e) {
  263. logger.error(filePath+"======="+e.getMessage(),e);
  264. }
  265. logger.info("解压结束================");
  266. return filePathList;
  267. }
  268. public static List<String> extractRar(String inputFilePath, String outputDirPath){
  269. List<String> fileList = new ArrayList<>();
  270. // 创建Archive对象,用于读取rar压缩文件格式
  271. try{
  272. Archive archive = new Archive(new FileInputStream(inputFilePath));
  273. // 读取压缩文件中的所有子目录或子文件(FileHeader对象)
  274. List<FileHeader> fileHeaderList = archive.getFileHeaders();
  275. // 遍历子目录和子文件
  276. for (FileHeader fd:fileHeaderList) {
  277. System.out.println(fd.getFileName());
  278. File f = new File(outputDirPath+"/"+fd.getFileName());
  279. if(fd.isDirectory()){
  280. // 创建新子目录
  281. f.mkdirs();
  282. }else{
  283. // 创建新子文件
  284. f.createNewFile();
  285. // 获取压缩包中的子文件输出流
  286. InputStream in = archive.getInputStream(fd);
  287. // 复制文件输入流至新子文件
  288. FileUtils.copyInputStreamToFile(in,f);
  289. fileList.add(f.getAbsolutePath());
  290. }
  291. }
  292. } catch (Exception e) {
  293. logger.error(e.getMessage(),e);
  294. //调用unrar命令解压
  295. try{
  296. unrar(inputFilePath,outputDirPath);
  297. File dir = new File(outputDirPath);
  298. for (File file : dir.listFiles()) {
  299. logger.info(file.getAbsolutePath());
  300. fileList.addAll(fileList(file));
  301. }
  302. }catch (Exception e1){
  303. logger.error(e.getMessage(),e1);
  304. }
  305. }
  306. return fileList;
  307. }
  308. private static List<String> fileList(File file){
  309. List<String> fileList = new ArrayList<>();
  310. if(file.isDirectory()){
  311. File[] files = file.listFiles();
  312. for (File file1 : files) {
  313. System.out.println(file1.getAbsolutePath());
  314. if(file1.isDirectory()){
  315. List<String> dirFileList = fileList(file1);
  316. fileList.addAll(dirFileList);
  317. }else{
  318. fileList.add(file1.getAbsolutePath());
  319. }
  320. }
  321. }else{
  322. fileList.add(file.getAbsolutePath());
  323. System.out.println(file.getAbsolutePath());
  324. }
  325. return fileList;
  326. }
  327. /**
  328. * 解压RAR文件
  329. * @param rarFilePath RAR文件路径
  330. * @param destDir 目标解压目录
  331. * @throws IOException 如果IO错误或解压失败
  332. * @throws InterruptedException 如果进程被中断
  333. */
  334. public static void unrar(String rarFilePath, String destDir) throws IOException, InterruptedException {
  335. // 确保目标目录存在
  336. File destDirFile = new File(destDir);
  337. if(!destDirFile.exists()){
  338. destDirFile.mkdirs();
  339. }
  340. // 构建解压命令
  341. ProcessBuilder processBuilder = new ProcessBuilder(
  342. "unrar", "x", "-o+", rarFilePath, destDir
  343. );
  344. processBuilder.redirectErrorStream(true); // 合并标准错误流和标准输出流
  345. // 执行命令
  346. Process process = processBuilder.start();
  347. // 读取命令输出(避免阻塞)
  348. try (BufferedReader reader = new BufferedReader(
  349. new InputStreamReader(process.getInputStream()))) {
  350. String line;
  351. while ((line = reader.readLine()) != null) {
  352. // 可选:处理输出信息(例如记录日志)
  353. System.out.println(line);
  354. }
  355. }
  356. // 等待命令执行完成
  357. int exitCode = process.waitFor();
  358. if (exitCode != 0) {
  359. throw new IOException("解压失败,退出码: " + exitCode);
  360. }
  361. }
  362. public static void writeDataToSheet(Sheet sheet, Elements rows) {
  363. int rowSize = rows.size();
  364. for (int rowNum = 0; rowNum < rowSize; rowNum++) {
  365. Row sheetRow = sheet.createRow(rowNum);
  366. Element elementRow = rows.get(rowNum);
  367. Elements cells = elementRow.select("td");
  368. if (cells.size() == 0) {
  369. cells = elementRow.select("th");
  370. }
  371. int cellSize = cells.size();
  372. for (int cellNum = 0; cellNum < cellSize; cellNum++) {
  373. Cell sheetRowCell = sheetRow.createCell(cellNum);
  374. sheetRowCell.setCellValue(cells.get(cellNum).text());
  375. }
  376. }
  377. }
  378. /**
  379. * 获取优先级高的字段值
  380. *
  381. * @param sheetRow 行
  382. * @param priorityPosition 字段位置
  383. * @param basePosition 优先级搞的字段位置
  384. * @return 优先级高的字段值
  385. */
  386. public static String getPriorityFieldValue(Row sheetRow, Integer priorityPosition, Integer basePosition) {
  387. boolean hasPriorityValue = priorityPosition != null && sheetRow.getCell(priorityPosition) != null && StrUtil.isNotBlank(ExcelUtil.getCellValue(sheetRow.getCell(priorityPosition)));
  388. if (hasPriorityValue) {
  389. return ExcelUtil.getCellValue(sheetRow.getCell(priorityPosition));
  390. }
  391. return basePosition != null && sheetRow.getCell(basePosition) != null ? ExcelUtil.getCellValue(sheetRow.getCell(basePosition)) : null;
  392. }
  393. /**
  394. * 去掉逗号
  395. *
  396. * @param numberData 数字型字符串
  397. * @return 无逗号的数字型字符串
  398. */
  399. public static String numberDataStripCommas(String numberData) {
  400. if (StrUtil.isBlank(numberData)) {
  401. return null;
  402. }
  403. // pdf解析到的值带有",",比如:"10,656,097.37"
  404. String data = numberData.replaceAll(",", "");
  405. if (!StringUtil.isNumeric(data)) {
  406. return null;
  407. }
  408. return data;
  409. }
  410. public static XSSFWorkbook getHSSFWorkbook(String sheetName, List<String> title, Map<String, List<List<String>>> valueMap, XSSFWorkbook wb) {
  411. // 第一步,创建一个HSSFWorkbook,对应一个Excel文件
  412. if (wb == null) {
  413. wb = new XSSFWorkbook();
  414. }
  415. try {
  416. // 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
  417. XSSFSheet sheet = wb.createSheet(sheetName);
  418. // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
  419. XSSFRow row = sheet.createRow(0);
  420. // 第四步,创建单元格,并设置值表头 设置表头居中
  421. XSSFCellStyle style = wb.createCellStyle();
  422. style.setAlignment(HorizontalAlignment.LEFT);
  423. style.setWrapText(true);
  424. sheet.setColumnWidth(0, 10000);
  425. sheet.setColumnWidth(1, 10000);
  426. sheet.setColumnWidth(2, 5000);
  427. sheet.setColumnWidth(3, 8000);
  428. sheet.setColumnWidth(4, 8000);
  429. sheet.setColumnWidth(5, 5000);
  430. //声明列对象
  431. XSSFCell cell = null;
  432. //创建标题
  433. for (int i = 0; i < title.size(); i++) {
  434. cell = row.createCell(i);
  435. cell.setCellValue(title.get(i));
  436. cell.setCellStyle(style);
  437. }
  438. int count = 65500;
  439. List<List<String>> values = valueMap.get(sheetName);
  440. //创建内容
  441. for (int i = 0; i < values.size(); i++) {
  442. row = sheet.createRow(i + 1);
  443. for (int j = 0; j < values.get(i).size(); j++) {
  444. //将内容按顺序赋给对应的列对象
  445. row.createCell(j).setCellValue(values.get(i).get(j));
  446. }
  447. if(i > count){
  448. break;
  449. }
  450. }
  451. } catch (Exception e) {
  452. logger.error(e.getMessage(), e);
  453. }
  454. return wb;
  455. }
  456. public static Sheet getFirstSheet(String filePath) {
  457. if (StrUtil.isBlank(filePath)) {
  458. return null;
  459. }
  460. try {
  461. File file = new File(filePath);
  462. return ExcelUtil.getSheet(file, 0);
  463. } catch (Exception e) {
  464. logger.error("获取文件的sheet错误 -> 文件路径:{},堆栈信息为:{}", filePath, ExceptionUtil.stacktraceToString(e));
  465. }
  466. return null;
  467. }
  468. public static String pdfConvertToExcel(String filePath, String excelFilePath) {
  469. File savefile = new File(excelFilePath);
  470. if (!savefile.exists()) {
  471. if (!savefile.getParentFile().exists()) {
  472. savefile.getParentFile().mkdirs();
  473. savefile.getParentFile().setExecutable(true);
  474. }
  475. }
  476. try (OutputStream outputStream = Files.newOutputStream(Paths.get(excelFilePath))) {
  477. PDDocument document = Loader.loadPDF(new File(filePath));
  478. PageIterator extract = new ObjectExtractor(document).extract();
  479. Workbook workbook = new XSSFWorkbook();
  480. Sheet sheet = workbook.createSheet("Sheet1");
  481. int preEndRowIndex =0;
  482. while (extract.hasNext()) {
  483. Page next = extract.next();
  484. List<technology.tabula.Table> tableList = new SpreadsheetExtractionAlgorithm().extract(next);
  485. for (technology.tabula.Table table : tableList) {
  486. List<List<RectangularTextContainer>> rows = table.getRows();
  487. int rowLength = rows.size();
  488. for (int rowNum = 0; rowNum < rowLength; rowNum++) {
  489. Row sheetRow = sheet.createRow(rowNum + preEndRowIndex);
  490. List<RectangularTextContainer> textContainerList = rows.get(rowNum);
  491. for (int cellNum = 0; cellNum < textContainerList.size(); cellNum++) {
  492. Cell cell = sheetRow.createCell(cellNum);
  493. RectangularTextContainer textContainer = textContainerList.get(cellNum);
  494. if (textContainer != null) {
  495. cell.setCellValue(textContainer.getText());
  496. }
  497. }
  498. }
  499. preEndRowIndex = preEndRowIndex + rowLength - 1 < 0 ? 0 : preEndRowIndex + rowLength - 1;
  500. }
  501. }
  502. // 将Excel工作簿写入输出流
  503. workbook.write(outputStream);
  504. } catch (Exception e) {
  505. logger.error("解析邮件pdf附件报错 -> 堆栈信息:{}", ExceptionUtil.stacktraceToString(e));
  506. return null;
  507. }
  508. return excelFilePath;
  509. }
  510. public static String contentConvertToExcel(String emailContent, String excelFilePath) {
  511. Elements rows;
  512. try {
  513. Document doc = Jsoup.parse(emailContent);
  514. Element table = doc.select("table").first();
  515. rows = table.select("tr");
  516. } catch (Exception e) {
  517. return null;
  518. }
  519. File saveFile = new File(excelFilePath);
  520. if (!saveFile.exists()) {
  521. if (!saveFile.getParentFile().exists()) {
  522. saveFile.getParentFile().mkdirs();
  523. saveFile.getParentFile().setExecutable(true);
  524. }
  525. }
  526. try (OutputStream outputStream = new FileOutputStream(saveFile)) {
  527. // 创建一个新的Excel工作簿
  528. Workbook workbook = new XSSFWorkbook();
  529. Sheet sheet = workbook.createSheet("Sheet1");
  530. ExcelUtil.writeDataToSheet(sheet, rows);
  531. // 将Excel工作簿写入输出流
  532. workbook.write(outputStream);
  533. } catch (Exception e) {
  534. logger.error("邮件正文转换成excel报错 -> 堆栈信息:{}", ExceptionUtil.stacktraceToString(e));
  535. return null;
  536. }
  537. return excelFilePath;
  538. }
  539. /**
  540. * 通过表头所在位置判断是行数据还是列数据
  541. *
  542. * @param fieldPositionMap excel中表头所在的位置
  543. * @return 行方向-1,,列方向-2
  544. */
  545. public static Integer detectDataDirection(Map<String, Pair<Integer, Integer>> fieldPositionMap) {
  546. long count = fieldPositionMap.values().stream().map(Pair::getValue).distinct().count();
  547. return count == 1 ? EmailDataDirectionConst.COLUMN_DIRECTION_TYPE : EmailDataDirectionConst.ROW_DIRECTION_TYPE;
  548. }
  549. // Excel 的起始日期是 1900 年 1 月 1 日
  550. private static final LocalDate EXCEL_EPOCH_DATE = LocalDate.of(1900, 1, 1);
  551. public static String convertExcelDateToString(String dateNum) {
  552. LocalDate startDate = LocalDate.of(1900, 1, 1);
  553. LocalDate localDate = startDate.plusDays(Math.round(Double.valueOf(dateNum) - 2));
  554. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
  555. return localDate.format(formatter);
  556. }
  557. public static XSSFWorkbook getProductXSSFWorkbook(List<ProductDataVO> productDataVOList) {
  558. // 第一步,创建一个HSSFWorkbook,对应一个Excel文件
  559. XSSFWorkbook wb = new XSSFWorkbook();
  560. try {
  561. createProductInfoSheet(wb,productDataVOList);
  562. createProductContractSheet(wb,productDataVOList);
  563. createProductDetailSheet(wb,productDataVOList);
  564. createInvestmentManagerSheet(wb,productDataVOList);
  565. }catch (Exception e) {
  566. logger.error(e.getMessage(),e);
  567. }
  568. return wb;
  569. }
  570. private static void createInvestmentManagerSheet(XSSFWorkbook wb, List<ProductDataVO> productDataVOList) {
  571. try{
  572. XSSFSheet sheet = wb.createSheet("投资经理信息");
  573. List<String> title = new ArrayList<>();
  574. title.add("编号");
  575. title.add("中基协基金编号");
  576. title.add("投资经理任职起始时间");
  577. title.add("投资经理任职结束时间");
  578. title.add("投资经理");
  579. //创建第一行
  580. XSSFRow row1 = sheet.createRow(0);
  581. XSSFRow row2 = sheet.createRow(1);
  582. for (int i = 0; i < title.size(); i++) {
  583. row1.createCell(i);
  584. row2.createCell(i);
  585. }
  586. XSSFCell firstCcell = row1.createCell(0);
  587. firstCcell.setCellValue("私募管理人数据推送信息填写(投资经理情况)");
  588. XSSFCellStyle style = wb.createCellStyle();
  589. Font font = wb.createFont();
  590. font.setFontName("微软");//设置字体
  591. font.setBold(true);//加粗
  592. font.setFontHeightInPoints((short) 12);//设置字体大小
  593. font.setBold(true);
  594. style.setFont(font);//设置单元格字体
  595. style.setAlignment(HorizontalAlignment.LEFT);
  596. style.setWrapText(true);
  597. firstCcell.setCellStyle(style);
  598. sheet.addMergedRegion(new CellRangeAddress(0,1,0,title.size()));
  599. XSSFRow row = sheet.createRow(2);
  600. sheet.setColumnWidth(0, 3000);
  601. sheet.setColumnWidth(1, 5000);
  602. sheet.setColumnWidth(2, 8000);
  603. sheet.setColumnWidth(3, 8000);
  604. sheet.setColumnWidth(4, 10000);
  605. //声明列对象
  606. XSSFCell cell = null;
  607. //创建标题
  608. for (int i = 0; i < title.size(); i++) {
  609. cell = row.createCell(i);
  610. cell.setCellValue(title.get(i));
  611. cell.setCellStyle(style);
  612. }
  613. int count = 65500;
  614. List<List<String>> values = new ArrayList<>();
  615. for (ProductDataVO productDataVO : productDataVOList) {
  616. List<InvestmentManagerVO> investmentManagerVOList = productDataVO.getInvestmentManagerVOList();
  617. for (InvestmentManagerVO investmentManagerVO : investmentManagerVOList) {
  618. List<String> valueList = new ArrayList<>();
  619. valueList.add(String.valueOf(investmentManagerVO.getId()));
  620. valueList.add(investmentManagerVO.getRegisterNumber());
  621. valueList.add(investmentManagerVO.getStartDate());
  622. valueList.add(investmentManagerVO.getEndDate());
  623. valueList.add(investmentManagerVO.getManagerName());
  624. values.add(valueList);
  625. }
  626. }
  627. //创建内容
  628. for (int i = 0; i < values.size(); i++) {
  629. row = sheet.createRow(i + 3);
  630. for (int j = 0; j < values.get(i).size(); j++) {
  631. //将内容按顺序赋给对应的列对象
  632. row.createCell(j).setCellValue(values.get(i).get(j));
  633. }
  634. if(i > count){
  635. break;
  636. }
  637. }
  638. } catch (Exception e) {
  639. logger.error(e.getMessage(), e);
  640. }
  641. }
  642. private static void createProductContractSheet(XSSFWorkbook wb, List<ProductDataVO> productDataVOList) {
  643. try{
  644. XSSFSheet sheet = wb.createSheet("产品合同信息");
  645. List<String> title = new ArrayList<>();
  646. title.add("编号");
  647. title.add("中基协基金编号");
  648. title.add("基金产品全名");
  649. title.add("基金合同");
  650. title.add("投资范围");
  651. title.add("投资限制");
  652. title.add("投资策略");
  653. title.add("投资方式");
  654. title.add("业绩比较基准");
  655. title.add("业绩报酬计提方式");
  656. title.add("备注");
  657. //创建第一行
  658. XSSFRow row1 = sheet.createRow(0);
  659. XSSFRow row2 = sheet.createRow(1);
  660. for (int i = 0; i < title.size(); i++) {
  661. row1.createCell(i);
  662. row2.createCell(i);
  663. }
  664. XSSFCell firstCcell = row1.createCell(0);
  665. firstCcell.setCellValue("私募管理人数据推送信息填写(其他信息)");
  666. XSSFCellStyle style = wb.createCellStyle();
  667. Font font = wb.createFont();
  668. font.setFontName("微软");//设置字体
  669. font.setBold(true);//加粗
  670. font.setFontHeightInPoints((short) 12);//设置字体大小
  671. font.setBold(true);
  672. style.setFont(font);//设置单元格字体
  673. style.setAlignment(HorizontalAlignment.LEFT);
  674. style.setWrapText(true);
  675. firstCcell.setCellStyle(style);
  676. sheet.addMergedRegion(new CellRangeAddress(0,1,0,title.size()));
  677. XSSFRow row = sheet.createRow(2);
  678. // 第四步,创建单元格,并设置值表头 设置表头居中
  679. sheet.setColumnWidth(0, 2000);
  680. sheet.setColumnWidth(1, 5000);
  681. sheet.setColumnWidth(2, 10000);
  682. sheet.setColumnWidth(3, 8000);
  683. sheet.setColumnWidth(4, 8000);
  684. sheet.setColumnWidth(5, 5000);
  685. sheet.setColumnWidth(6, 5000);
  686. sheet.setColumnWidth(7, 5000);
  687. sheet.setColumnWidth(8, 5000);
  688. sheet.setColumnWidth(9, 8000);
  689. sheet.setColumnWidth(10, 5000);
  690. //声明列对象
  691. XSSFCell cell = null;
  692. //创建标题
  693. for (int i = 0; i < title.size(); i++) {
  694. cell = row.createCell(i);
  695. cell.setCellValue(title.get(i));
  696. cell.setCellStyle(style);
  697. }
  698. int count = 65500;
  699. List<List<String>> values = new ArrayList<>();
  700. for (ProductDataVO productDataVO : productDataVOList) {
  701. ProductContractVO productContractVO = productDataVO.getProductContractVO();
  702. List<String> valueList = new ArrayList<>();
  703. valueList.add(String.valueOf(productContractVO.getId()));
  704. valueList.add(productContractVO.getRegisterNumber());
  705. valueList.add(productContractVO.getProductName());
  706. valueList.add(productContractVO.getProductContract());
  707. valueList.add(productContractVO.getInvestmentScope());
  708. valueList.add(productContractVO.getInvestmentLimit());
  709. valueList.add(productContractVO.getInvestmentStrategy());
  710. valueList.add(productContractVO.getInvestmentMethod());
  711. valueList.add(productContractVO.getPerformanceBasic());
  712. valueList.add(productContractVO.getAccruedMethod());
  713. valueList.add(productContractVO.getRemark());
  714. values.add(valueList);
  715. }
  716. //创建内容
  717. for (int i = 0; i < values.size(); i++) {
  718. row = sheet.createRow(i + 3);
  719. for (int j = 0; j < values.get(i).size(); j++) {
  720. //将内容按顺序赋给对应的列对象
  721. row.createCell(j).setCellValue(values.get(i).get(j));
  722. }
  723. if(i > count){
  724. break;
  725. }
  726. }
  727. } catch (Exception e) {
  728. logger.error(e.getMessage(), e);
  729. }
  730. }
  731. private static void createProductDetailSheet(XSSFWorkbook wb, List<ProductDataVO> productDataVOList) {
  732. try{
  733. XSSFSheet sheet = wb.createSheet("产品其他信息");
  734. List<String> title = new ArrayList<>();
  735. title.add("编号");
  736. title.add("中基协基金编号");
  737. title.add("基金产品全名");
  738. title.add("成立分红拆分清算公告");
  739. title.add("复权净值");
  740. title.add("产品份额");
  741. title.add("产品总资产");
  742. title.add("估值表");
  743. title.add("投资经理投资年限起始日(即最早对外募集资金并投资之日)");
  744. title.add("投资经理从业经历");
  745. title.add("投资经理在管数量");
  746. title.add("公司总管理规模");
  747. title.add("申购/赎回费率");
  748. title.add("管理人费率");
  749. title.add("托管费率");
  750. title.add("外包费率");
  751. //创建第一行
  752. XSSFRow row1 = sheet.createRow(0);
  753. XSSFRow row2 = sheet.createRow(1);
  754. for (int i = 0; i < title.size(); i++) {
  755. row1.createCell(i);
  756. row2.createCell(i);
  757. }
  758. XSSFCell firstCcell = row1.createCell(0);
  759. firstCcell.setCellValue("私募管理人数据推送信息填写(其他信息)");
  760. XSSFCellStyle style = wb.createCellStyle();
  761. Font font = wb.createFont();
  762. font.setFontName("微软");//设置字体
  763. font.setBold(true);//加粗
  764. font.setFontHeightInPoints((short) 12);//设置字体大小
  765. font.setBold(true);
  766. style.setFont(font);//设置单元格字体
  767. style.setAlignment(HorizontalAlignment.LEFT);
  768. style.setWrapText(true);
  769. firstCcell.setCellStyle(style);
  770. sheet.addMergedRegion(new CellRangeAddress(0,1,0,title.size()));
  771. XSSFRow row = sheet.createRow(2);
  772. sheet.setColumnWidth(0, 3000);
  773. sheet.setColumnWidth(1, 5000);
  774. sheet.setColumnWidth(2, 10000);
  775. sheet.setColumnWidth(3, 8000);
  776. sheet.setColumnWidth(4, 8000);
  777. sheet.setColumnWidth(5, 5000);
  778. sheet.setColumnWidth(6, 5000);
  779. sheet.setColumnWidth(7, 5000);
  780. sheet.setColumnWidth(8, 17000);
  781. sheet.setColumnWidth(9, 8000);
  782. sheet.setColumnWidth(10, 8000);
  783. sheet.setColumnWidth(11, 5000);
  784. sheet.setColumnWidth(12, 5000);
  785. sheet.setColumnWidth(13, 5000);
  786. sheet.setColumnWidth(14, 5000);
  787. sheet.setColumnWidth(15, 5000);
  788. //声明列对象
  789. XSSFCell cell = null;
  790. //创建标题
  791. for (int i = 0; i < title.size(); i++) {
  792. cell = row.createCell(i);
  793. cell.setCellValue(title.get(i));
  794. cell.setCellStyle(style);
  795. }
  796. int count = 65500;
  797. List<List<String>> values = new ArrayList<>();
  798. for (ProductDataVO productDataVO : productDataVOList) {
  799. ProductDerivativeVO productDerivativeVO = productDataVO.getProductDerivativeVO();
  800. List<String> valueList = new ArrayList<>();
  801. valueList.add(String.valueOf(productDerivativeVO.getId()));
  802. valueList.add(productDerivativeVO.getRegisterNumber());
  803. valueList.add(productDerivativeVO.getProductName());
  804. valueList.add(productDerivativeVO.getDistributeReport());
  805. valueList.add(productDerivativeVO.getCumulativeNav());
  806. valueList.add(productDerivativeVO.getProductShare());
  807. valueList.add(productDerivativeVO.getProductAsset());
  808. valueList.add(productDerivativeVO.getProductValuation());
  809. valueList.add(productDerivativeVO.getStartDate());
  810. valueList.add(productDerivativeVO.getInvestmentManagerDesc());
  811. valueList.add(productDerivativeVO.getProductCount());
  812. valueList.add(productDerivativeVO.getManageAsset());
  813. valueList.add(productDerivativeVO.getFeeNote());
  814. valueList.add(productDerivativeVO.getManagementfeeTrust());
  815. valueList.add(productDerivativeVO.getManagementfeeBank());
  816. valueList.add(productDerivativeVO.getOutsourceFee());
  817. values.add(valueList);
  818. }
  819. //创建内容
  820. for (int i = 0; i < values.size(); i++) {
  821. row = sheet.createRow(i + 3);
  822. for (int j = 0; j < values.get(i).size(); j++) {
  823. //将内容按顺序赋给对应的列对象
  824. row.createCell(j).setCellValue(values.get(i).get(j));
  825. }
  826. if(i > count){
  827. break;
  828. }
  829. }
  830. } catch (Exception e) {
  831. logger.error(e.getMessage(), e);
  832. }
  833. }
  834. private static void createProductInfoSheet(XSSFWorkbook wb, List<ProductDataVO> productDataVOList) {
  835. try{
  836. XSSFSheet sheet = wb.createSheet("产品基本信息");
  837. List<String> title = new ArrayList<>();
  838. title.add("编号");
  839. title.add("中基协基金编号");
  840. title.add("基金产品全名");
  841. title.add("成立日期");
  842. title.add("清盘日期");
  843. title.add("母子基金标签");
  844. title.add("是否结构化产品");
  845. title.add("基金一级分类");
  846. title.add("基金二级分类");
  847. title.add("基金三级分类");
  848. title.add("投资策略变更情况说明");
  849. title.add("现任投资经理");
  850. title.add("任职起始日期");
  851. title.add("净值数据提供频率");
  852. title.add("基金资产净值提供频率");
  853. title.add("定期报告");
  854. title.add("备注");
  855. //创建第一行
  856. XSSFRow row1 = sheet.createRow(0);
  857. XSSFRow row2 = sheet.createRow(1);
  858. for (int i = 0; i < title.size(); i++) {
  859. row1.createCell(i);
  860. row2.createCell(i);
  861. }
  862. XSSFCell firstCcell = row1.createCell(0);
  863. firstCcell.setCellValue("私募管理人数据推送信息填写(产品基本信息)");
  864. XSSFCellStyle style = wb.createCellStyle();
  865. Font font = wb.createFont();
  866. font.setFontName("微软");//设置字体
  867. font.setBold(true);//加粗
  868. font.setFontHeightInPoints((short) 12);//设置字体大小
  869. font.setBold(true);
  870. style.setFont(font);//设置单元格字体
  871. style.setAlignment(HorizontalAlignment.LEFT);
  872. style.setWrapText(true);
  873. firstCcell.setCellStyle(style);
  874. sheet.addMergedRegion(new CellRangeAddress(0,1,0,title.size()));
  875. XSSFRow row = sheet.createRow(2);
  876. sheet.setColumnWidth(0, 3000);
  877. sheet.setColumnWidth(1, 10000);
  878. sheet.setColumnWidth(2, 10000);
  879. sheet.setColumnWidth(3, 8000);
  880. sheet.setColumnWidth(4, 8000);
  881. sheet.setColumnWidth(5, 5000);
  882. sheet.setColumnWidth(6, 10000);
  883. sheet.setColumnWidth(7, 5000);
  884. sheet.setColumnWidth(8, 5000);
  885. sheet.setColumnWidth(9, 5000);
  886. sheet.setColumnWidth(10, 15000);
  887. sheet.setColumnWidth(11, 5000);
  888. sheet.setColumnWidth(12, 5000);
  889. sheet.setColumnWidth(13, 10000);
  890. sheet.setColumnWidth(14, 10000);
  891. sheet.setColumnWidth(15, 5000);
  892. sheet.setColumnWidth(16, 5000);
  893. //声明列对象
  894. XSSFCell cell = null;
  895. //创建标题
  896. for (int i = 0; i < title.size(); i++) {
  897. cell = row.createCell(i);
  898. cell.setCellValue(title.get(i));
  899. cell.setCellStyle(style);
  900. }
  901. int count = 65500;
  902. List<List<String>> values = new ArrayList<>();
  903. for (ProductDataVO productDataVO : productDataVOList) {
  904. ProductInformationVO productInformationVO = productDataVO.getProductInformationVO();
  905. List<String> valueList = new ArrayList<>();
  906. valueList.add(String.valueOf(productInformationVO.getId()));
  907. valueList.add(productInformationVO.getRegisterNumber());
  908. valueList.add(productInformationVO.getProductName());
  909. valueList.add(productInformationVO.getInceptionDate());
  910. valueList.add(productInformationVO.getLiquidateDate());
  911. valueList.add(productInformationVO.getMsLabel());
  912. valueList.add(productInformationVO.getIsStruct());
  913. valueList.add(productInformationVO.getFirstStrategy());
  914. valueList.add(productInformationVO.getSecondStrategy());
  915. valueList.add(productInformationVO.getThirdStrategy());
  916. valueList.add(productInformationVO.getInvestmentStrategyDesc());
  917. valueList.add(productInformationVO.getInvestmentManager());
  918. valueList.add(productInformationVO.getStartDate());
  919. valueList.add(productInformationVO.getNavFrequency());
  920. valueList.add(productInformationVO.getAssetFrequency());
  921. valueList.add(productInformationVO.getReportFrequency());
  922. valueList.add(productInformationVO.getRemark());
  923. values.add(valueList);
  924. }
  925. //创建内容
  926. for (int i = 0; i < values.size(); i++) {
  927. row = sheet.createRow(i + 3);
  928. for (int j = 0; j < values.get(i).size(); j++) {
  929. //将内容按顺序赋给对应的列对象
  930. row.createCell(j).setCellValue(values.get(i).get(j));
  931. }
  932. if(i > count){
  933. break;
  934. }
  935. }
  936. } catch (Exception e) {
  937. logger.error(e.getMessage(), e);
  938. }
  939. }
  940. public static boolean isImage(String fileName) {
  941. return StrUtil.isNotBlank(fileName) && (fileName.endsWith("jpg") || fileName.endsWith("JPG") || fileName.endsWith("PNG") || fileName.endsWith("png"));
  942. }
  943. }