我正在使用spring上传Excel文件,但是apache无法读取该文件,因为它要么损坏,要么以不同的格式读取。但只有当我上传Excel文件时才会发生这种情况。Excel文件在上传之前就会打开。使用POI版本3.17的Iam
这是我的密码。
HTML
<form method="post" action="/uploadExcelFile" enctype="multipart/form-data">
<div id="categoriesForMessages" class="row">
<div class="col-sm-12">
<label>Upload File</label>
<input id="form-control-9" name="file" type="file" accept=".xls,.xlsx">
<p class="help-block">
<small>Upload Excel types .xls .xlsx</small>
</p>
</div>
</form>控制器
public class XController {
@PostMapping("/uploadExcelFile")
public String uploadFile(Model model, MultipartFile file) throws IOException {
File currDir = new File(".");
String path = currDir.getAbsolutePath();
fileLocation = path.substring(0, path.length() - 1) + file.getOriginalFilename();
System.out.println(fileLocation);
FileOutputStream f = new FileOutputStream(fileLocation);
try {
FileInputStream fis = new FileInputStream(fileLocation);
Workbook workbook = WorkbookFactory.create(fis);
fis.close();
Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(0);
System.out.println(row.getCell(0).getStringCellValue());
} catch (InvalidFormatException e) {
e.printStackTrace();
}
return "redirect:/home";
}
}发布于 2018-05-08 10:25:52
代码的问题在于,您正在尝试读取刚才创建的空文件。但是,您应该阅读multipart-file来创建工作簿。
FileInputStream fis = new FileInputStream(fileLocation); // fis created with new file location
Workbook workbook = WorkbookFactory.create(fis); //creating a workbook with an empty file如果您试图从工作簿中读取,您可以直接使用MultipartFile对象并完成它。不需要创建新的File。
做这样的事。
Workbook workbook = WorkbookFactory.create(file.getInputStream());然后继续处理这个文件。如果你想把文件保存在某个地方,你可以这样做,
try (FileOutputStream outputStream = new FileOutputStream("/path/to/your/file/hello.xlsx")) {
workbook.write(outputStream);
}https://stackoverflow.com/questions/50230764
复制相似问题