poi导入excel

àì夳堔傛蜴生んèń 2022-06-03 00:48 349阅读 0赞

pox导入excel

  1. @FunctionalInterface
  2. public interface ImportHandlerCallback<V> {
  3. /** * 数据校验、VO构建 * * @param error_index 出现错误或警告的行索引 * @param values 根据树据行解析出的数组 * @return */
  4. V preHandle(int error_index, String[] values);
  5. }
  6. public abstract class ImportHandler<V> {
  7. /** * @param filename 文件名 * @param is InputStream * @param importHandlerCallback * @return */
  8. public abstract List<V> handle(String filename, InputStream is, ImportHandlerCallback<V> importHandlerCallback);
  9. }
  10. public class ExcelImportHandler<V> extends ImportHandler<V> {
  11. private static final Logger logger = LoggerFactory.getLogger(ExcelImportHandler.class);
  12. @Override
  13. public List<V> handle(String filename, InputStream is, ImportHandlerCallback<V> importHandlerCallback) {
  14. if (filename == null || filename.length() == 0){
  15. throw new RuntimeException("文件名为空,导入操作失败!");
  16. }
  17. logger.info("开始解析Excel文件:" + filename);
  18. if (is == null){
  19. throw new RuntimeException("文件流为空,导入操作失败!");
  20. }
  21. if (importHandlerCallback == null) {
  22. throw new RuntimeException("无预处理参数配置,导入操作失败!");
  23. }
  24. Workbook workBook;
  25. try {
  26. String file_suffix = ExcelUtil.getExtensionName(filename);
  27. if (!ExcelUtil.isExcel(file_suffix)){
  28. throw new RuntimeException("请上传后缀:[xls,xlsx]文件!");
  29. }
  30. workBook = ExcelUtil.getWeebWork(is, file_suffix);
  31. } catch (IOException e) {
  32. throw new RuntimeException("读取文件工作簿失败,导入操作失败!");
  33. }
  34. if (workBook == null) {
  35. throw new RuntimeException("工作簿为空,导入操作失败!");
  36. }
  37. Sheet sheet = workBook.getSheetAt(0);
  38. if (sheet == null) {
  39. throw new RuntimeException("Sheet为空,导入操作失败!");
  40. }
  41. // 获取表格中的数据,按数据行构造VOList对象
  42. List<V> preExecution = new ArrayList<V>();
  43. Iterator<Row> it = sheet.rowIterator();
  44. int row_index = 0;
  45. int cell_count = 0;
  46. while (it.hasNext()) {
  47. Row row = it.next();
  48. //跳过第一行
  49. if (row.getRowNum() == 0) {
  50. row_index++;
  51. cell_count = row.getLastCellNum();
  52. continue;
  53. }
  54. String[] tmp = new String[cell_count];
  55. for (int i = 0; i < cell_count; i++) {
  56. Cell cell = row.getCell(i);
  57. String value = ExcelUtil.getCellValue(cell);
  58. if (value == null || value.length() == 0){
  59. logger.warn("Excel解析空数据警告。【行索引:" + (row_index + 1) + ",列索引:" + (i + 1) + "】");
  60. }
  61. tmp[i] = value;
  62. }
  63. V v = importHandlerCallback.preHandle((row_index + 1), tmp);
  64. row_index++;
  65. preExecution.add(v);
  66. }
  67. return preExecution;
  68. }
  69. }
  70. public class ExcelUtil {
  71. public static final String[] excel_suffixes = new String[]{
  72. "xls", "xlsx"};
  73. public static Workbook getWeebWork(InputStream is, String file_suffix) throws IOException {
  74. Workbook workbook = null;
  75. if (null != is) {
  76. if (file_suffix.toLowerCase().equals("xls")) {
  77. workbook = new HSSFWorkbook(is);
  78. }
  79. if (file_suffix.toLowerCase().equals("xlsx")) {
  80. workbook = new XSSFWorkbook(is);
  81. }
  82. }
  83. return workbook;
  84. }
  85. public static String getCellValue(Cell cell) {
  86. String value = null;
  87. if (null != cell) {
  88. // 以下是判断数据的类型
  89. switch (cell.getCellType()) {
  90. case Cell.CELL_TYPE_NUMERIC: // 数字
  91. if (HSSFDateUtil.isCellDateFormatted(cell)) {
  92. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  93. Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(cell.getNumericCellValue());
  94. value = sdf.format(date);
  95. } else {
  96. value = cell.getNumericCellValue() + "";
  97. value = BigDecimal.valueOf(Double.parseDouble(value)).stripTrailingZeros().toPlainString();
  98. }
  99. break;
  100. case Cell.CELL_TYPE_STRING: // 字符串
  101. value = cell.getStringCellValue() + "";
  102. break;
  103. case Cell.CELL_TYPE_BOOLEAN: // Boolean
  104. value = cell.getBooleanCellValue() + "";
  105. break;
  106. case Cell.CELL_TYPE_FORMULA: // 公式
  107. value = cell.getCellFormula() + "";
  108. break;
  109. case Cell.CELL_TYPE_BLANK: // 空值
  110. break;
  111. case Cell.CELL_TYPE_ERROR: // 故障
  112. break;
  113. default:
  114. break;
  115. }
  116. }
  117. return value == null ? "" : value;
  118. }
  119. public static String getExtensionName(String filename) {
  120. if (filename != null && filename.length() > 0) {
  121. int dot = filename.lastIndexOf('.');
  122. if (dot > -1 && dot < (filename.length() - 1)) {
  123. return filename.substring(dot + 1).toLowerCase();
  124. }
  125. }
  126. return null;
  127. }
  128. public static boolean isExcel(String file_suffix) {
  129. if (file_suffix == null) return false;
  130. for (String s : excel_suffixes) {
  131. if (file_suffix.equals(s)) {
  132. return true;
  133. }
  134. }
  135. return false;
  136. }
  137. public static Date formatDate(String date) {
  138. try {
  139. if (date == null || date.length() == 0) return null;
  140. date = date.replace("/", "-").replace("年", "-").replace("月", "").replace("日", "");
  141. SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
  142. if (date.indexOf("-") <= 0) df = new SimpleDateFormat("yyyyMMdd");
  143. return df.parse(date);
  144. } catch (ParseException e) {
  145. e.printStackTrace();
  146. throw new RuntimeException("日期格式错误:[" + date + "]");
  147. }
  148. }
  149. }

发表评论

表情:
评论列表 (有 0 条评论,349人围观)

还没有评论,来说两句吧...

相关阅读

    相关 poi批量导入excel

    1.先下载poi依赖的包,复制张贴代码一定没有错误 2.直接上代码,如果导入有错误,可能是别人给你发的excel模版有错误,可以自己创建一个excel测试