How to read excel file using spring boot

Manish Bansal :

I am making a spring boot application which will take the excel file and store its content and store it in database. I have tried many ways..but not successful. Is anyone has idea how to do this. I don't know how to make the controller for importing the excel file. And is there any dependency which i have to include for reading data from excel file

Manish Bansal :

Finally found the solution.

Html file for uploading the form is

<form th:action="@{/import}" method="post" enctype="multipart/form-data">

    <input type="file" th:name="file">

<input th:type="submit" value="Import" />

Controller class is

@PostMapping("/import")
public void mapReapExcelDatatoDB(@RequestParam("file") MultipartFile reapExcelDataFile) throws IOException {

   List<Test> tempStudentList = new ArrayList<Test>();
    XSSFWorkbook workbook = new XSSFWorkbook(reapExcelDataFile.getInputStream());
    XSSFSheet worksheet = workbook.getSheetAt(0);

    for(int i=1;i<worksheet.getPhysicalNumberOfRows() ;i++) {
        Test tempStudent = new Test();

        XSSFRow row = worksheet.getRow(i);

        tempStudent.setId((int) row.getCell(0).getNumericCellValue());
        tempStudent.setContent(row.getCell(1).getStringCellValue());
            tempStudentList.add(tempStudent);   
    }
}

Make sure to add the dependecy

        <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.12</version>
    </dependency>
    <!-- excel 2007 over-->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.12</version>
    </dependency>

Now it will work fine.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=464981&siteId=1