英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论