首页 > 解决方案 > 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";
    }
}

标签: javaexcelspring-bootapache-poithymeleaf

解决方案


您的代码的问题是您正在尝试读取刚刚创建的空文件。但是您应该已经阅读了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);
}

推荐阅读