如何使用Spring Boot读取Excel文件 [英] How to read excel file using spring boot

查看:651
本文介绍了如何使用Spring Boot读取Excel文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个Spring Boot应用程序,它将使用excel文件并存储其内容并将其存储在数据库中.我尝试了很多方法..但没有成功.有谁知道如何做到这一点. 我不知道如何制作用于导入Excel文件的控制器.而且从Excel文件读取数据是否需要包含任何依赖项

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

推荐答案

最终找到了解决方案.

用于上传表单的HTML文件是

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" />
</form>

控制器类是

@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);   
    }
}

确保添加依赖项

<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>

现在它将正常工作.

这篇关于如何使用Spring Boot读取Excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆