2

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.

Aoon
  • 21
  • 2
  • Looks like your file isn't actually a XLSX file... If you open it up in Excel and do a Save-As, what format type does Excel think it is? – Gagravarr Oct 07 '20 at 08:25
  • @Gagravarr actually, it's working fine on the func but it failed on the test. i don't know why – Aoon Oct 07 '20 at 10:00

1 Answers1

1

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