SpringBoot은 POI를 이용하여 Excel 파일 데이터를 mysql 데이터베이스로 가져옵니다.

7804 단어 SpringBoot
SpringBoot을 처음 배워서 잘 모르는데 잘못된 점이 있으면 지적해 주세요.
더 이상 말하지 말고 코드로 바로 올라가세요.
서비스 계층
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

좋은 웹페이지 즐겨찾기