springBoot+springDataJpa将Excel导入MySql数据库

1、新建一个springBoot项目

pom.xml依赖配置

org.springframework.boot

spring-boot-starter-data-jpa

org.springframework.boot

spring-boot-starter-web

mysql

mysql-connector-java

5.1.45

com.alibaba

druid

1.1.12

org.mybatis.spring.boot

mybatis-spring-boot-starter

1.2.2

org.springframework.boot

spring-boot-starter-test

test

org.junit.vintage

junit-vintage-engine

org.apache.poi

poi

3.15

org.apache.poi

poi-ooxml

3.15

commons-logging

commons-logging

1.2

org.projectlombok

lombok

1.18.12

provided

org.springframework.boot

spring-boot-starter-thymeleaf

2、数据库配置

#mysql配置

spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.url=jdbc:mysql://47.92.245.9:3306/peo-test?&useUnicode=true&characterEncoding=UTF-8

spring.datasource.username=root

spring.datasource.password=Btkx1234!

spring.jpa.hibernate.ddl-auto=update

spring.jpa.hibernate.show-sql=true

spring.jpa.show-sql=true

#druid 数据源

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

#编码格式设置

spring.thymeleaf.encoding=UTF-8

3、配置静态页面

在项目的resources/templates/excelImport.html下

页面内容:

Excel导入

选择Excel表格:

4、DAO层

import com.java.excel.Entity.Excel;

import org.springframework.data.jpa.repository.JpaRepository;

public interface ExcelDaoextends JpaRepository {

}

5、service层

@Service

//事务控制

@Transactional

public class ExcelService {

@Autowired

private ExcelDaoexcelDao;

public void saveExcel(MultipartFile file)throws IOException {

//根据路径获取这个操作excel的实例

//      HSSFWorkbook wb = new HSSFWorkbook(file.getInputStream());

        XSSFWorkbook work =new XSSFWorkbook(file.getInputStream());

//根据页面index 获取sheet页

//      HSSFSheet sheet = wb.getSheetAt(0);

        XSSFSheet sheet = work.getSheetAt(0);

//        HSSFSheet 和XSSFSheet 是有区别的,自行百度

         XSSFRow row =null;//接受每一行的数据    

        for (int i =1; i < sheet.getPhysicalNumberOfRows(); i++) {

             //获取每一行数据

             row = sheet.getRow(i);

            //要判断每一行数据是否为空,此处没写,自行百度

             row.getCell(0);//拿到每一列

            //拿到每一列后放入对应的实体中,新增

        }

}

6、controller层

@Controller

public class ExcelController {

    @Autowired

    private ExcelServiceexcelService;

    @GetMapping("/toHtml")

    public String test(HttpServletRequest request) {

        return "excelImport";

    }

    //处理文件上传

    @ResponseBody//返回json数据

    @RequestMapping(value ="/excelImport", method = RequestMethod.POST)

    public String uploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) {

        String contentType = file.getContentType();

        String fileName = file.getOriginalFilename();

    if (file.isEmpty()) {

    return "文件为空!";

    }

    try {

        excelService.saveExcel(file);

    }catch (Exception e) {

        e.printStackTrace();

    }

        return "导入成功!";

    }

}

你可能感兴趣的:(springBoot+springDataJpa将Excel导入MySql数据库)