SpringBoot利用POI将Excel文件数据导入mysql数据库

初学SpringBoot,对其不太了解,有什么不对请指正。

不多说,直接上代码。

Service层

package com.happy.service;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Repository;

import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Repository
public class ImportService {

    private final static String excel2003 =".xls";
    private final static String excel2007 =".xlsx";

    /**
     * @param in
     * @param fileName
     * 处理上传的excel文件
     *
    * */
    public  List> getBankListByExcel(InputStream in, String fileName) throws Exception{
        List> list = null;
        //创建Excel工作薄
        Workbook work = this.getWorkbook(in,fileName);
        if(null == work){
            throw new Exception("创建Excel工作薄为空!");
        }
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;

        list = new ArrayList>();
        for (int i = 0; i < work.getNumberOfSheets(); i++) {
            sheet = work.getSheetAt(i);
            if(sheet==null){continue;}

            for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
                row = sheet.getRow(j);
                if(row==null||row.getFirstCellNum()==j){continue;}

                List li = new ArrayList();
                for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
                    cell = row.getCell(y);
                    li.add(cell);
                }
                list.add(li);
            }
        }
        work.close();
        return list;
    }
    //判断excel文件的格式
    public  Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{
        Workbook wb = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if(excel2003.equals(fileType)){
            wb = new HSSFWorkbook(inStr);
        }else if(excel2007.equals(fileType)){
            wb = new XSSFWorkbook(inStr);
        }else{
            throw new Exception("解析的文件格式有误!");
        }
        return wb;
    }
} Controller 
  
package com.happy.controller;

import com.happy.entity.User;
import com.happy.mapper.UserMapper;
import com.happy.service.ImportService;
import com.happy.util.ExcelImportUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.List;

@Controller
public class ImportController {

    @RequestMapping("/index")
    public String index(){
        return "index";
    }
    @Autowired
    private ImportService importService;
    @Autowired
    private  User user;
    @Autowired
    private UserMapper userMapper;

    @RequestMapping(value="/upload",method=RequestMethod.POST)
    public  @ResponseBody String  uploadExcel(HttpServletRequest request) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        InputStream inputStream =null;
        List> list = null;
        MultipartFile file = multipartRequest.getFile("filename");
        if(file.isEmpty()){
           return "文件不能为空";
        }
        inputStream = file.getInputStream();
        list = importService.getBankListByExcel(inputStream,file.getOriginalFilename());
        inputStream.close();
//连接数据库部分
        for (int i = 0; i < list.size(); i++) {
            List lo = list.get(i);
            userMapper.insert(String.valueOf(lo.get(0)),String.valueOf(lo.get(1)),String.valueOf(lo.get(2)));
            //调用mapper中的insert方法
        }
            return "上传成功";
    }

} Mapper类 
  
package com.happy.mapper;

import com.happy.entity.User;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

@Mapper
@Repository
public interface UserMapper {
    //查询数据
    @Select("SELECT * FROM USER WHERE PHONE = #{phone}")
    User findUserByPhone(@Param("phone") String phone);
    //添加数据
    @Insert("INSERT INTO USER(NAME, PASSWORD, PHONE) VALUES(#{name}, #{password}, #{phone})")
    int insert(@Param("name") String name, @Param("password") String password, @Param("phone") String phone);

}
实体类
package com.happy.entity;

public class User {

    private Integer id;
    private String name;
    private String password;
    private String phone;

//省略get/set

}
前台



    
    上传文件


POM文件


	4.0.0

	com.winterchen
	springboot-mybatis-demo2
	0.0.1-SNAPSHOT
	jar

	springboot-mybatis-demo2
	Demo project for Spring Boot

	
		org.springframework.boot
		spring-boot-starter-parent
		1.5.8.RELEASE
		 
	

	
		UTF-8
		UTF-8
		1.8
	

	
		
			org.mybatis.spring.boot
			mybatis-spring-boot-starter
			1.3.1
		

		
			mysql
			mysql-connector-java
			runtime
		
		
			org.springframework.boot
			spring-boot-starter-test
			test
		
		
			org.springframework.boot
			spring-boot-starter-thymeleaf
		
		
			org.apache.poi
			poi
			3.13
		
		
			org.apache.poi
			poi-ooxml
			3.13
		
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	


数据库配置

spring:
  datasource:
     url: jdbc:mysql://127.0.0.1:3306/数据库名
     username: 数据库账号
     password: 密码
     driver-class-name: com.mysql.jdbc.Driver




你可能感兴趣的:(SpringBoot)