ExcelUtil.java 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package cn.efunbox.base.util;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  4. import org.apache.poi.ss.usermodel.Cell;
  5. import org.apache.poi.ss.usermodel.CellType;
  6. import org.apache.poi.ss.usermodel.Workbook;
  7. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  8. import org.springframework.web.multipart.MultipartFile;
  9. import java.io.IOException;
  10. import java.util.Objects;
  11. /**
  12. * ExcelUtil
  13. * Created by xusq on 2020/9/14.
  14. */
  15. @Slf4j
  16. public class ExcelUtil {
  17. private final static String EXCEL_2003 = ".xls"; //2003- 版本的excel
  18. private final static String EXCEL_2007 = ".xlsx"; //2007+ 版本的excel
  19. public static Workbook getWorkbook(MultipartFile file) {
  20. Workbook wb = null;
  21. String fileName = file.getOriginalFilename();
  22. String fileType = fileName.substring(fileName.lastIndexOf("."));
  23. try {
  24. if (EXCEL_2003.equals(fileType)) {
  25. wb = new HSSFWorkbook(file.getInputStream()); //2003-
  26. } else if (EXCEL_2007.equals(fileType)) {
  27. wb = new XSSFWorkbook(file.getInputStream()); //2007+
  28. }
  29. } catch (IOException e) {
  30. log.error("find input stream is error , {}",e.getMessage(),e);
  31. }
  32. return wb;
  33. }
  34. /**
  35. * 单表值获取
  36. *
  37. * @param cell 获取
  38. * @return 类型
  39. */
  40. public static String getCell(Cell cell) {
  41. if (Objects.nonNull(cell)) {
  42. CellType cellType = cell.getCellTypeEnum();
  43. if (cellType == CellType.STRING) {//字符串类型
  44. //System.out.println(cell.getStringCellValue());
  45. return cell.getStringCellValue().trim();
  46. }
  47. if (cellType == CellType.NUMERIC) {//数字类型
  48. long numericCellValue = (long) cell.getNumericCellValue();
  49. //System.out.println(numericCellValue);
  50. return numericCellValue + "";
  51. }
  52. }
  53. return null;
  54. }
  55. }