java - Spring在上传到服务器时损坏了Excel(xlsx,xls)文件(org.apache.poi)
问题描述
我正在使用 spring 上传 Excel 文件,但 apache POI 无法读取该文件,因为它已损坏或格式不同。但这仅在我上传 Excel 文件时发生。Excel 文件在上传之前就已打开。我正在使用 POI 3.17 版
这是我的代码。
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";
}
}
解决方案
您的代码的问题是您正在尝试读取刚刚创建的空文件。但是您应该已经阅读了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);
}
推荐阅读
- arduino - Arduino 串行打印始终在串行监视器上显示变量 0
- debugging - 当我想在 vs 代码中以调试模式运行 donnet core 应用程序时出现问题
- azure-data-factory - Azure 数据工厂将管道处理的文件作为邮件附件传递给逻辑应用
- sqlalchemy - 炼金术。获取插入的默认值
- java - 从Java中固定格式的字符串中提取数字
- reactjs - 创建 Stepper,将 next 和 back 作为 onClick-event 处理
- amazon-web-services - 是否可以更改存储在 AWS S3 存储桶中的图像的 url 路径名?
- python - pygame 不会在我的 pymunk 模拟中画出我的圆圈
- javascript - 等待回调结束而不嵌套
- amazon-web-services - dynamoDB 是否对受限制的请求收费?