Неверная подпись заголовка при чтении любого файла xls - PullRequest
0 голосов
/ 05 мая 2020

Когда я пытаюсь прочитать файл xls, используя приведенный ниже код, я всегда получаю сообщение об ошибке: org. apache .poi.poifs.filesystem.NotOLE2FileException: недопустимая подпись заголовка; прочтите 0x65572D2D2D2D2D2D, ожидается 0xE11AB1A1E011CFD0 - Ваш файл не является действительным документом OLE2.

Это мой код:

public Result<List<IDto>> ReadExcelClassInfo2003(File file,
            Timestamp createTime, Timestamp updateTime, BigDecimal createBy,
            BigDecimal updateBy) {

        Result<List<IDto>> resultData = new Result<List<IDto>>();
        Integer numInsertSuccess = 0;

        if (file == null) {
            resultData.setErrorCode(ErrorCode.ERROR_FORMAT);
            return resultData;
        }
        try {

            InputStream is = new FileInputStream(file);
            POIFSFileSystem fs = new POIFSFileSystem(is);
            Integer classType = ClassTypeEnum.CLASSROOM.getValue();
            Integer maxCol = ExcelConstant.MAX_COLUMN_CLASSROOM_INFO;

            workbook = new HSSFWorkbook(fs);
            HSSFSheet sheetClassInfo = workbook
                    .getSheetAt(0);

            if (sheetClassInfo == null) {
                resultData.setErrorCode(ErrorCode.ERROR_FORMAT);
                return resultData;
            }

            //Some code to get data from excel file here.


            is.close();
            workbook.close();
        } catch (FileNotFoundException e) {
            resultData.setErrorCode(ErrorCode.ERROR_FORMAT);
            return resultData;
        } catch (IOException e) {
            resultData.setErrorCode(ErrorCode.ERROR_FORMAT);
            return resultData;
        } catch (Exception e) {
            resultData.setErrorCode(ErrorCode.ERROR_FORMAT);
            return resultData;
        }

        if (numInsertSuccess == 0) {
            resultData.setErrorCode(ErrorCode.CLASS_DATA_INVALID);
            return resultData;
        }

        resultData.setErrorCode(ErrorCode.IMPORT_SUCCESS);
        resultData.setMessage(numInsertSuccess.toString());

        return resultData;
    }

Мой код контроллера:

@POST
    @Path("class/import")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Produces(MediaType.APPLICATION_JSON)
    @RolesAllowed(Role.TRAINING_ADMIN)
//  public Response importClass(@FormParam("file") File file) {
    public Response importClass(@Multipart("file") File file) {
        LOGGER.info("Received PUT import class: file=" + file.length());
        if (checkTokenAndRole(new int[] {1, 11}).getStatus() != Response.Status.OK.getStatusCode()) {           
            return LoginError(checkToken().getStatus());                
        } else {
            String token = request.getHeader(HttpHeaders.AUTHORIZATION);
            String fileExtension = request.getHeader("FileExtension");
            return ClassService.getInstance().importClass(file, fileExtension,
                    token);
        }
    }

И метод вызывается контроллером:

public Response importClass(File file, String fileExtension, String token) {
        Result<List<IDto>> result = new Result<List<IDto>>();
        try {

            ErrorDTO errorDto = new ErrorDTO();
            String data = "";

            double bytes = file.length();
            double kilobytes = (bytes / 1024);
            double megabytes = (kilobytes / 1024);
            if (megabytes > ExcelConstant.MAX_FILE_SIZE) {
                errorDto.setErrorCode(ErrorCode.ERROR_FORMAT);
                data = Utility.toJSONString(errorDto);

                return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                        .entity(data).build();
            }

            Timestamp createTime = new Timestamp(System.currentTimeMillis());
            Timestamp updateTime = new Timestamp(System.currentTimeMillis());
            BigDecimal createBy = null;
            BigDecimal updateBy = null;

            Result<UserInfoDTO> userInfo = DaoManager.getUserInfoDao()
                    .getUserInfoByToken(token);
            if (userInfo.getData() != null) {
                createBy = userInfo.getData().getId();
                updateBy = userInfo.getData().getId();
            }

            result = DaoManager.getClassDao().importClass(file, fileExtension,
                    createTime, updateTime, createBy, updateBy);

            int errorCode = result.getErrorCode();
            String message = result.getMessage();


            errorDto = new ErrorDTO();
            errorDto.setErrorCode(errorCode);
            errorDto.setMessage(message);
            data = Utility.toJSONString(errorDto);

            // release memory
            userInfo = null;
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                    .entity(data).build();

        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
            result.setStatus(Constant.INTERNAL_SERVER_ERROR);
            result.setErrorCode(ErrorCode.IMPORT_ERROR);

            return super.responseData(result);
        }

    }
public Result<List<IDto>> importClass(File file, String fileExtension,
            Timestamp createTime, Timestamp updateTime, BigDecimal createBy,
            BigDecimal updateBy) throws IOException {

        return ExportExcelService.getInstance().ReadExcelClassInfo2003(file,
                fileExtension, createTime, updateTime, createBy, updateBy);
    }

Я отладил и обнаружил, что процесс всегда проверяет новую POIFSFileSystem и генерирует исключение с ошибкой выше. Я тестировал все файлы xls, которые у меня есть, и у меня такая же ошибка. Любой может помочь мне решить эту проблему, и какой заголовок 0x65572D2D2D2D2D2D?

Спасибо.

...