如何解决 NotOfficeXmlFileException 问题

huangapple go评论83阅读模式
英文:

how to solve NotOfficeXmlFileException

问题

我有一个用于将Excel文件上传到服务器并读取其内容的API,因此我的代码如下:

public ReturnSTH funcExample(@RequestParam("file") MultipartFile file) {
    Sheet sheet = null;
    try {
        InputStream in = file.getInputStream();
        Workbook workbook = new XSSFWorkbook(in);
        sheet = workbook.getSheetAt(0);
    } catch (IOException e) {
        // 处理异常
    }
}

然后我需要使用JUnit来测试API,如下所示:

@Test
public void test() {
    MockMultipartFile fakeFile = new MockMultipartFile("file", "bank.xlsx", MediaType.TEXT_PLAIN_VALUE, "file data".getBytes());
    ReturnSTH response = funcExample(fakeFile);
}

我遇到了以下错误:

org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException: 未找到有效的条目或内容,这不是有效的OOXML(Office Open XML)文件

出现在 Workbook workbook = new XSSFWorkbook(in); 这一行。

我不知道如何解决这个问题。

英文:

I have an API for uploading excel file to a server and read it, so my code below

public ReturnSTH funcExample(@RequestParam("file") MultipartFile file) {
    Sheet sheet = null;
    try {
        InputStream in = file.getInputStream();
        Workbook workbook = new XSSFWorkbook(in);
        sheet = workbook.getSheetAt(0);
    } catch (IOException e) {
        // do something
    }

then I have to test the API using JUnit as below

@Test
public void test() {
	MockMultipartFile fakeFile = new MockMultipartFile("file", "bank.xlsx", MediaType.TEXT_PLAIN_VALUE, "file data".getBytes());
	ReturnSTH response = funcExample(fakeFile);
}

I got the error like below

org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException: No valid entries or contents found, this is not a valid OOXML (Office Open XML) file

on the line Workbook workbook = new XSSFWorkbook(in);

I don't know how to fix this issue.

答案1

得分: 1

我为测试解决了这个问题:

String originalName = "src/main/resources/test.xlsx";
File testFile = new File(originalName);
InputStream stream = new FileInputStream(testFile);
MockMultipartFile file = new MockMultipartFile("file", testFile.getName(), MediaType.ALL_VALUE, stream);

只需使用 FileInputStream 并使用 .xlsx 格式。

英文:

I solved this for test:

String originalName = "src/main/resources/test.xlsx";
    File testFile = new File(originalName);
    InputStream stream = new FileInputStream(testFile);
    MockMultipartFile file = new MockMultipartFile("file", testFile.getName(), MediaType.ALL_VALUE, stream);

Just use FileInputStream and use .xlsx format

huangapple
  • 本文由 发表于 2020年10月7日 11:59:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/64236995.html
匿名

发表评论

匿名网友

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

确定