无效的文件头签名,在读取任何xls文件时出现

huangapple 未分类评论49阅读模式
英文:

Invalid header signature when read any xls file

问题

以下是翻译好的内容:

当我尝试使用下面的代码读取 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;
            }
            
            // 从 Excel 文件中获取数据的一些代码在这里。
            
            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(@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);

        // 释放内存
        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 是什么?

谢谢。

英文:

When I try to read xls file using the code below, I always get error:
org.apache.poi.poifs.filesystem.NotOLE2FileException: Invalid header signature; read 0x65572D2D2D2D2D2D, expected 0xE11AB1A1E011CFD0 - Your file appears not to be a valid OLE2 document.

This is my code:

public Result&lt;List&lt;IDto&gt;&gt; ReadExcelClassInfo2003(File file,
			Timestamp createTime, Timestamp updateTime, BigDecimal createBy,
			BigDecimal updateBy) {

		Result&lt;List&lt;IDto&gt;&gt; resultData = new Result&lt;List&lt;IDto&gt;&gt;();
		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;
	}

My controller code :

@POST
    @Path(&quot;class/import&quot;)
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Produces(MediaType.APPLICATION_JSON)
    @RolesAllowed(Role.TRAINING_ADMIN)
//  public Response importClass(@FormParam(&quot;file&quot;) File file) {
    public Response importClass(@Multipart(&quot;file&quot;) File file) {
        LOGGER.info(&quot;Received PUT import class: file=&quot; + 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(&quot;FileExtension&quot;);
            return ClassService.getInstance().importClass(file, fileExtension,
                    token);
        }
    }

And the method are call by controller :

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

            ErrorDTO errorDto = new ErrorDTO();
            String data = &quot;&quot;;

            double bytes = file.length();
            double kilobytes = (bytes / 1024);
            double megabytes = (kilobytes / 1024);
            if (megabytes &gt; 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&lt;UserInfoDTO&gt; 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&lt;List&lt;IDto&gt;&gt; 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);
    }

I debuged and found the process always check new POIFSFileSystem and throw exception with error above. I tested with all xls file I have and have same error.
Any can help me resolve this problem, and what the header 0x65572D2D2D2D2D2D ?

Thanks.

huangapple
  • 本文由 发表于 2020年5月5日 10:59:38
  • 转载请务必保留本文链接:https://java.coder-hub.com/61604995.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定