记录 SpringBoot Jar包部署上传文件,预览文件(访问服务器文件)和 POI 解析 Excel

上传文件

FileUtil 工具类

public class FileUtil {

    public static String getUploadFilePath(String path) throws FileNotFoundException {
        File pathRoot = new File(ResourceUtils.getURL("classpath:").getPath());
        if(!pathRoot.exists()) {
            pathRoot = new File("");
        }
        String realPath = pathRoot.getAbsolutePath().replace("%20"," ")
                .replace('/', '\\')+"\\upload\\"+path+"\\";
        File f = new File(realPath);
        if(!f.exists()) {
            f.mkdirs();
        }
        return realPath;
    }
}

上传接口

@PostMapping("/import")
    public ApiResponse enterpriseImport(@NotNull(message = "文件不能为空") MultipartFile file, HttpServletRequest request) throws IOException {
        if (file.isEmpty()) {
            throw new FileException(CommonCode.FILE_EMPTY);
        }
        String path = FileUtil.getUploadFilePath("excel");
        String fileName = file.getOriginalFilename();
        File targetFile = new File(path + fileName);
        file.transferTo(targetFile);
        return enterpriseService.importEnterprise(targetFile);
    }

ExcelUtil 工具类

public class ExcelUtil {

  private static final String EXCEL_XLS = "xls";
  private static final String EXCEL_XLSX = "xlsx";


  public static Workbook getWorkbook(File file) throws IOException {
      FileInputStream fileStream = new FileInputStream(file);
      if(file.getName().endsWith(EXCEL_XLS)) {
          return new HSSFWorkbook(fileStream);
      } else if(file.getName().endsWith(EXCEL_XLSX)){
          return new XSSFWorkbook(fileStream);
      }
      return null;
  }

  /**
   * 读取单元格的值
   * @param cell 单元格
   * @return string
   */
  public static String getCellValue(Cell cell) {
      Object result = "";
      if (cell != null) {
          switch (cell.getCellType()) {
              case Cell.CELL_TYPE_STRING:
                  result = cell.getStringCellValue();
                  break;
              case Cell.CELL_TYPE_NUMERIC:
                  result = cell.getNumericCellValue();
                  break;
              case Cell.CELL_TYPE_BOOLEAN:
                  result = cell.getBooleanCellValue();
                  break;
              case Cell.CELL_TYPE_FORMULA:
                  result = cell.getCellFormula();
                  break;
              case Cell.CELL_TYPE_ERROR:
                  result = cell.getErrorCellValue();
                  break;
              case Cell.CELL_TYPE_BLANK:
                  break;
              default:
                  break;
          }
      }
      return result.toString();
  }
}

POI 解析 Excel

// 错误信息
      StringBuilder errorMsg = new StringBuilder();
      List<Enterprise> list = new ArrayList<>();
      Workbook workbook = null;
      try {
          workbook = ExcelUtil.getWorkbook(file);
      } catch (IOException e) {
          throw new FileException(CommonCode.FILE_ERROR);
      }
      if (workbook == null) {
          throw new FileException(CommonCode.FILE_ERROR);
      }
      // 只获取第一个
      Sheet sheet = workbook.getSheetAt(0);
      // 从第二行开始,第一行为表头
      for (int i = 1; i <= sheet.getLastRowNum(); i++) {
          try {
              // 业务逻辑
              list.add(enterprise);

          } catch (Exception e) {
              e.printStackTrace();
              errorMsg.append("【第").append(i).append("行 数据解析失败】");
          }
      }
      // 检查文件解析是否有误
      if (StringUtils.isNotBlank(errorMsg.toString()) || list.size() == 0) {
          // TODO 抛出异常
          return new ApiFailResponse(errorMsg.toString());
      }
      mapper.insertBatch(list);
      return new ApiMessageResponse(CommonCode.SUCCESS);
  }

MyBatis 批量插入

 <insert id="insertBatch">
        insert into
            gs_enterprise(xxx,xxx,xxx)
        values
        <foreach collection ="list" item="xx" separator =",">
            (#{xx.xxx},#{xx.xxx},#{xx.xxx})
        </foreach >
    </insert>

预览文件(访问服务器本地文件)

SpringMVC 配置

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    private String path = FileUtil.getUploadFilePath("pdf");

    public WebMvcConfig() throws FileNotFoundException {
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/file/preview/*")
                .addResourceLocations("file:"+path);
    }
}

访问方式:IP地址:端口/file/priview/文件名

参考博客:是夏天呀!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值