1、easyexcel[导出]

  1. 1、需引入依赖
  2. <dependency>
  3. <groupId>com.alibaba</groupId>
  4. <artifactId>easyexcel</artifactId>
  5. <version>2.1.6</version>
  6. </dependency>
  7. 2Demo
  8. public class ExcelUtils {
  9. /**
  10. * 导出文件
  11. * @param response 文件写入流
  12. * @param fileName 文件名
  13. * @param sheetName 分栏名
  14. * @param excelClass excel映射类
  15. * @param excelData 导出数据
  16. * @throws IOException
  17. */
  18. public static void exportExcelData(HttpServletResponse response, String fileName, String sheetName, Class excelClass, List excelData) throws IOException {
  19. response.setContentType("application/vnd.ms-excel");
  20. response.setCharacterEncoding("utf-8");
  21. String name = URLEncoder.encode(fileName, "UTF-8");
  22. response.setHeader("Content-disposition", "attachment;filename=" + name + ".xlsx");
  23. WriteCellStyle headWriteCellStyle = new WriteCellStyle();
  24. headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
  25. WriteFont headWriteFont = new WriteFont();
  26. headWriteFont.setFontName("宋体");
  27. headWriteFont.setFontHeightInPoints((short) 14);
  28. headWriteFont.setBold(true);
  29. headWriteCellStyle.setWriteFont(headWriteFont);
  30. WriteCellStyle writeCellStyle = new WriteCellStyle();
  31. writeCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
  32. HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, Arrays.asList(writeCellStyle));
  33. EasyExcel.write(response.getOutputStream(), excelClass)
  34. .autoCloseStream(Boolean.FALSE).sheet(sheetName)
  35. .registerWriteHandler(horizontalCellStyleStrategy)
  36. .doWrite(excelData);
  37. }
  38. }

2、apache-poi[导入]

  1. public RealtimeResultModel readExcel(MultipartFile multipartFile, Long projectId, String labelSource, String userId, Long tenantId, Long sceneId)
  2. {
  3. //工作簿
  4. Workbook workbook = null;
  5. InputStream inputstream = null;
  6. //获取当前方法的方法名称
  7. String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
  8. //返回客户端文件系统中的原始文件名,可能包含路径信息
  9. String fileName = multipartFile.getOriginalFilename();
  10. try
  11. {
  12. // 获取excel后缀名
  13. inputstream = multipartFile.getInputStream();
  14. //Excel 2007, 最大支持1048576行
  15. if (fileName.endsWith("xlsx")){
  16. workbook = new XSSFWorkbook(inputstream);
  17. }
  18. //Excel 2003, 最大支持65536行
  19. else if (fileName.endsWith("xls")){
  20. workbook = new HSSFWorkbook(inputstream);
  21. }
  22. if(Objects.isNull(workbook))
  23. {
  24. LoggerUtil.warn(LOGGER, "readExcel()中, 构建workbook对象为空, 文件名:{0}", fileName);
  25. return new RealtimeResultModel < Long > (false, 0 L, "构建workbook对象为空");
  26. }
  27. Map < String, Object > resultMap = new HashMap < > ();
  28. // 解析sheet[存在多个sheet时]
  29. int numberOfSheets = workbook.getNumberOfSheets();
  30. LoggerUtil.warn(LOGGER, "readexcel()中, 上传的excel文件中, sheet数目={0}, 文件名:{1}", numberOfSheets, fileName);
  31. for(int sheetnum = 0; sheetnum < numberOfSheets; sheetnum++)
  32. {
  33. //得到一个工作表
  34. Sheet sheet = workbook.getSheetAt(sheetnum);
  35. // 校验sheet是否合法
  36. if(sheet == null)
  37. {
  38. continue;
  39. }
  40. //获得表头
  41. Row rowHead = sheet.getRow(sheetnum);
  42. //判断表头是否正确【getPhysicalNumberOfCells():获取有记录的列数,比如:最后有数据的列是第n列,前面有m列是空列没数据,则返回n-m;】
  43. if(4 != rowHead.getPhysicalNumberOfCells())
  44. {
  45. LoggerUtil.warn(LOGGER, "readexcel()中, 第{0}sheet, 的表头数量不为4, 文件名:{1}", sheetnum, fileName);
  46. continue;
  47. }
  48. //获得数据的总行数【如果sheet中一行数据都没有则返回-1,只有第一行有数据则返回0,最后有数据的行是第n行则返回 n-1】
  49. int totalRowNum = sheet.getLastRowNum() + 1;
  50. if(totalRowNum > 2000)
  51. {
  52. LoggerUtil.warn(LOGGER, "excel文件中的数据不允许超过两千条, 超出数目:{0}, 文件名:{1}", totalRowNum - 2000, fileName);
  53. }
  54. //获得第一行的数据的总行数【第一行0开始】
  55. int firstRowNum = sheet.getFirstRowNum() + 1;
  56. //获取有记录的行数【最后有数据的行是第n行,前面有m行是空行没数据,则返回n-m】
  57. int rowEnd = sheet.getPhysicalNumberOfRows();
  58. //要获得属性
  59. String platform = "";
  60. String projectName = "";
  61. String jobName = "";
  62. String customName = "";
  63. //满足校验条件的任务名称集合
  64. List < DqDatalinkRealtimeJobDO > withJobNameList = new ArrayList < > ();
  65. //不满足校验条件的任务名称集合
  66. List < String > noWithJobNameList = new ArrayList < > ();
  67. //总共insert or update 表【dq_datalink_realtime_job】的总数目
  68. int totalOperateCount = 0;
  69. //遍历获取每一行的数据
  70. for(int rowNum = firstRowNum; rowNum < rowEnd; rowNum++)
  71. {
  72. //获得第i行对象
  73. Row row = sheet.getRow(rowNum);
  74. if(Objects.isNull(row))
  75. {
  76. LoggerUtil.warn(LOGGER, "readexcel()中, 第{0}行数据为空, 文件名:{1}", rowNum, fileName);
  77. continue;
  78. }
  79. //获得获得第i行第0列的 String类型对象【任务归属平台】
  80. Cell cell = row.getCell((short) 0);
  81. platform = cell.getStringCellValue();
  82. //获得获得第i行第0列的 String类型对象【任务所属项目名】
  83. cell = row.getCell((short) 1);
  84. projectName = cell.getStringCellValue();
  85. //获得获得第i行第2列的 String类型对象【任务名称】
  86. cell = row.getCell((short) 2);
  87. jobName = cell.getStringCellValue();
  88. //获得获得第i行第3列的 String类型对象【关联标签】
  89. cell = row.getCell((short) 3);
  90. customName = cell.getStringCellValue();
  91. JobDTO jobInfo = new JobDTO();
  92. String subjectUrl = "";
  93. Long customId = 0 L;
  94. boolean validateResult = validateCellData(platform, projectName, jobName, customName, projectId, labelSource, customId, jobInfo, subjectUrl);
  95. if(validateResult)
  96. {
  97. //构建表[dq_datalink_realtime_job]操作实体对象
  98. DqDatalinkRealtimeJobDO dqDatalinkRealtimeJobDO = buildInsertRealtimeInfo(jobInfo, subjectUrl, userId, jobName, projectName, platform, methodName, tenantId, projectId, sceneId, customId);
  99. withJobNameList.add(dqDatalinkRealtimeJobDO);
  100. totalOperateCount += doRealtimeTaskTableDDL(dqDatalinkRealtimeJobDO, projectName, sceneId, jobName);
  101. }
  102. else
  103. {
  104. noWithJobNameList.add(jobName);
  105. }
  106. }
  107. LoggerUtil.info(LOGGER, "上传文件中:{0}, 新增或更新数据的总数目:{1}", fileName, totalOperateCount);
  108. Set < String > collectSet = withJobNameList.stream().map(DqDatalinkRealtimeJobDO::getDpJobName).collect(Collectors.toSet());
  109. resultMap.put("检验通过的任务名称", StringUtils.join(collectSet, ","));
  110. resultMap.put("检验不通过的任务名称", StringUtils.join(noWithJobNameList, ","));
  111. }
  112. return new RealtimeResultModel < Map < String, Object >> (true, resultMap, "构建workbook对象成功");
  113. }
  114. catch(Exception e)
  115. {
  116. LoggerUtil.warn(LOGGER, "解析excel失败,文件名:{0}, 错误信息:{1}", fileName, e.getMessage());
  117. return new RealtimeResultModel < Long > (false, 0 L, "上传文件处理失败");
  118. }
  119. finally
  120. {
  121. try
  122. {
  123. if(null != workbook)
  124. {
  125. workbook.close();
  126. }
  127. if(null != inputstream)
  128. {
  129. inputstream.close();
  130. }
  131. }
  132. catch(Exception e)
  133. {
  134. LoggerUtil.warn(LOGGER, "关闭数据流出错!错误信息:{0}", e.getMessage());
  135. }
  136. }

3、详细资料

1、支持.xlsx/.xls批量导入 1.1、poi、 https://blog.csdn.net/m0_61601521/article/details/123215591 https://www.jb51.net/article/119071.htm http://www.jszja.com/contents/14/2707.html http://www.zzvips.com/article/177224.html http://www.360doc.com/content/21/0527/16/75508165_979253054.shtml

  1. 1.2easyexcel
  2. [https://www.csdn.net/tags/MtjaggxsMjQwNzgtYmxvZwO0O0OO0O0O.html](https://www.csdn.net/tags/MtjaggxsMjQwNzgtYmxvZwO0O0OO0O0O.html)
  3. [https://wenku.baidu.com/view/d2768cebd938376baf1ffc4ffe4733687e21fc6f.html](https://wenku.baidu.com/view/d2768cebd938376baf1ffc4ffe4733687e21fc6f.html)
  4. [https://blog.csdn.net/gongzi_9/article/details/123104402](https://blog.csdn.net/gongzi_9/article/details/123104402)