Home » excel » java – Spring corrupts Excel(xlsx, xls) file when uploading to the server (org.apache.poi)

java – Spring corrupts Excel(xlsx, xls) file when uploading to the server (org.apache.poi)

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am uploading an Excel file using spring but apache POI cannot read the file because its either corrupt or in a different format. but this only happens when I upload the Excel file. the Excel file opens well before its uploaded. Iam using POI version 3.17

Here is my Code.

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>

Controller

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";
    }
}
How to&Answers:

The problem with your code is that you are trying to read an empty file which you have just created. But you should have read the multipart-file to create the workbook.

       FileInputStream fis = new FileInputStream(fileLocation); // fis created with new file location 
        Workbook workbook = WorkbookFactory.create(fis); //creating a workbook with an empty file

If you are trying to read from the workbook, You can directly make use of the MultipartFile object and be done with it. No need to create a new File.

Do something like this.

  Workbook workbook = WorkbookFactory.create(file.getInputStream());

and then go on and work with the file. If you want to save the file somewhere, you can do it like,

try (FileOutputStream outputStream = new FileOutputStream("/path/to/your/file/hello.xlsx")) {
            workbook.write(outputStream);
}