上传到服务器时,Spring会破坏Excel(xlsx,xls)文件(org.apache.poi)

时间:2018-05-08 09:52:21

标签: java excel spring-boot apache-poi thymeleaf

我使用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";
    }
}

1 个答案:

答案 0 :(得分:2)

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