SpringBoot Excel 파일 대량 업로드 데이터베이스 가 져 오기

Spring boot + Spring data jpa + Thymeleaf
일괄 삽입+POI 읽 기+파일 업로드
pom.xml:

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
 <groupId>org.apache.poi</groupId>
 <artifactId>poi</artifactId>
 <version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
 <groupId>org.apache.poi</groupId>
 <artifactId>poi-ooxml</artifactId>
 <version>3.17</version>
</dependency>
upload.html:

<form enctype="multipart/form-data" method="post" action="/upload/excel">
   
 <input type="file" name="file" /> <input type="submit" value="  " />
</form>
하면,만약,만약...  security,페이지 에서 파일 을 제출 하면 403 의 오류 가 발생 합 니 다.가장 빠 른 해결 방법 은 다음 과 같 습 니 다.

http.csrf().ignoringAntMatchers("/upload/**").
security 설정 파일 에 위의 코드 를 추가 하면 됩 니 다.물론 다른 방법 도 있 으 니 인터넷 에서 찾 아 보 세 요. 
Controller:

package org.meng.project.controller;
 
import org.meng.project.service.ExcelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletRequest;
 
/**
 *<p><b>  Controller </b></p>
 *<p>      Controller</p>
 * @Author MengMeng 
 * @Date 2018/10/6 </p>
 * @version: 0.1
 * @since JDK 1.80_144
 */
@Controller
@RequestMapping("/upload")
public class UploadController {
 @Autowired
 private HttpServletRequest request;
 
 @Autowired
 private ExcelService excelService;
 
 
 //          
 @RequestMapping(value = "", method = RequestMethod.GET)
 public String goUpload() {
 //    templates  tools     upload.html
 return "tools/upload";
 }
 
 
 
 @RequestMapping(value = "/excel",method = RequestMethod.POST)
 public String upload(MultipartFile file, Model model) throws Exception {
 
 boolean flag = excelService.getExcel(file);
 
 if(flag){
  model.addAttribute("Message", "    ");
 }else{
  model.addAttribute("Message", "    ");
 }
 
 return "tools/upload";
 }
 
}
Excel 실체:

package org.meng.project.entity;
 
import javax.persistence.*;
import java.io.Serializable;
import java.util.Objects;
 
/**
 * <p><b>     </b></p>
 * @ClassName User
 * @Author MengMeng 
 * @Date 2018/10/6 </p>
 * @Version: 0.1
 * @Since JDK 1.80_171
 */
 
@Entity
@Table(name = "test", schema = "project")
public class Excel implements Serializable {
 
 private static final long serialVersionUID = 1L;
 
 @Id
 @Column(length=36)
 private String id;
 
 @Column(length=45,nullable=false,unique=true)
 private String username;
 
 @Column(length=100,nullable=false,unique=true)
 private String email;
 
 @Column(length=45,nullable=false)
 private String password;
 
 @Column(length=45)
 private String role;
 
 public Excel() {
 }
 
 public Excel(Excel user){
  this.id = user.getId();
  this.username = user.getUsername();
  this.role = user.getRole();
  this.email = user.getEmail();
  this.password = user.getPassword();
 }
 
 //get   set
}
Service:

package org.meng.project.service;
 
import com.alibaba.fastjson.JSON;
 
import org.meng.project.entity.*;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
 
/**
 *<p><b>Excel Service   </b></p>
 *<p> Excel Service   , Excel         </p>
 * @Author MengMeng 
 * @Date 2018/10/6 </p>
 * @version: 0.1
 * @since JDK 1.80_144
 */
public interface ExcelService {
 
 boolean getExcel(MultipartFile file) throws Exception;
 
}
ServiceImpl:

package org.meng.project.service;
 
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.meng.project.entity.*;
import org.meng.project.repository.ExcelRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
 
import java.io.IOException;
import java.util.*;
 
/**
 * <p><b>Excel Service </b></p>
 * <p>Excel Service , User         </p>
 * @Author MengMeng
 * @Date 2018/10/6
 * @version: 0.1
 * @since JDK 1.80_144
 */
@Service
public class ExcelServiceImpl implements ExcelService {
 
 @Autowired
 private ExcelRepository excelRepository;
 
 @Override
 public boolean getExcel(MultipartFile file) throws Exception {
 // TODO Auto-generated method stub
 List<Excel> list = new ArrayList<Excel>();
 
  //1.      
  Workbook workbook2 = WorkbookFactory.create(file.getInputStream());
  //2、  test   
  Sheet sheet2 = workbook2.getSheet("test");
  //       
  int num = sheet2.getLastRowNum();
  //System.out.println(num);
  //   
  int col = sheet2.getRow(0).getLastCellNum();
 
 
  //  excel   
  for (int j = 0; j <= num; j++) {
  Row row1 = sheet2.getRow(j);
  
  //                  ,   setCellType()   string  
  Cell cell1 = row1.getCell(0);
  cell1.setCellType(CellType.STRING);
  //     i , 2     
  Cell cell2 = row1.getCell(1);
  //excel   i , 3     
  Cell cell3 = row1.getCell(2);
  cell3.setCellType(CellType.STRING);
  Cell cell4 = row1.getCell(3);
  Cell cell5 = row1.getCell(4);
  
  //  new     ,          Excel  ,       excel  
  Excel excel= new Excel();
  excel.setId(cell1.getStringCellValue());
  excel.setEmail(cell2.getStringCellValue());
  excel.setPassword(cell3.getStringCellValue());
  excel.setRole(cell4.getStringCellValue());
  excel.setUsername(cell5.getStringCellValue());
  list.add(excel);
 }
 
  excelRepository.saveAll(list);
 return true;
 }
}
메모:데이터베이스 와 Excel 표 의 데이터 값 형식 을 통일 해 야 합 니 다.그렇지 않 으 면 Cannot get a STRING value from a NUMERIC cell 등의 오류 가 발생 할 수 있 습 니 다.
Repository:

package org.meng.project.repository;
 
import org.meng.project.entity.Excel;
import org.meng.project.repository.base.BaseRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
 
/**
 *<p><b>Excel DAO   </b></p>
 *<p> Excel DAO   , Excel          </p>
 * @Author MengMeng 
 * @Date 2018/10/6 </p>
 * @version: 0.1
 * @since JDK 1.80_144
 */
@Repository
public interface ExcelRepository extends BaseRepository<Excel, String> {
 
 
}
파일 업로드 가능:

이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기