SpringBoot에서 Excel 가져오기 및 내보내기 방법

8405 단어 SpringBoot
우선, Pox를 설정해야 합니다.xml 파일의 종속성:
	
		commons-fileupload
		commons-fileupload
		1.3.1
	
	
	
	
		org.projectlombok
		lombok
	
	
	
	
		com.alibaba
		fastjson
		1.2.30
	
	
        cn.afterturn
        easypoi-base
        3.0.3
    
    
        cn.afterturn
        easypoi-web
        3.0.3 
    
        cn.afterturn
        easypoi-annotation
        3.0.3
    

그런 다음 ExcelUtiles를 가져옵니다.java 도구 클래스(자체 제작):

package com.hfut.utiles;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;

public class ExcelUtiles {
	public static void exportExcel(List> list, String title, String sheetName, Class> pojoClass,
            String fileName, boolean isCreateHeader, HttpServletResponse response){
					ExportParams exportParams = new ExportParams(title, sheetName);
					exportParams.setCreateHeadRows(isCreateHeader);
					defaultExport(list, pojoClass, fileName, response, exportParams);
					}
					
					public static void exportExcel(List> list, String title, String sheetName, Class> pojoClass,String fileName,
					            HttpServletResponse response){
					defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
					}
					
					public static void exportExcel(List> list, String fileName, HttpServletResponse response){
					defaultExport(list, fileName, response);
					}
					
					private static void defaultExport(List> list, Class> pojoClass, String fileName,
					               HttpServletResponse response, ExportParams exportParams) {
					Workbook workbook = ExcelExportUtil.exportExcel(exportParams,pojoClass,list);
					if (workbook != null); downLoadExcel(fileName, response, workbook);
					}
					
					private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
					try {
					response.setCharacterEncoding("UTF-8");
					response.setHeader("content-Type", "application/vnd.ms-excel");
					response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
					workbook.write(response.getOutputStream());
					} catch (IOException e) {
					//throw new NormalException(e.getMessage());
					}
					}
					
					private static void defaultExport(List> list, String fileName, HttpServletResponse response) {
					Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
					if (workbook != null);
					downLoadExcel(fileName, response, workbook);
					}
					
					public static  List importExcel(String filePath,Integer titleRows,Integer headerRows, Class pojoClass){
					if (StringUtils.isBlank(filePath)){
					return null;
					}
					ImportParams params = new ImportParams();
					params.setTitleRows(titleRows);
					params.setHeadRows(headerRows);
					List list = null;
					try {
					list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
					}catch (NoSuchElementException e){
					//throw new NormalException(" ");
					} catch (Exception e) {
					e.printStackTrace();
					//throw new NormalException(e.getMessage());
					} return list;
					}
					
					public static  List importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class pojoClass){
					if (file == null){ return null;
					}
					ImportParams params = new ImportParams();
					params.setTitleRows(titleRows);
					params.setHeadRows(headerRows);
					List list = null;
					try {
					list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
					}catch (NoSuchElementException e){
					// throw new NormalException("excel ");
					} catch (Exception e) {
					//throw new NormalException(e.getMessage());
					System.out.println(e.getMessage());
					}
					return list;
}
}



그런 다음 Entity의 클래스를 구성합니다.


package com.hfut.entity;
import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;

import javax.persistence.*;
import java.util.Date;

@SuppressWarnings("unused")
@Entity
@Table(name = "seckill")
public class User {
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Excel(name=" ",orderNum="0")
	private int id;
	
	@Column(name="name")
	@Excel(name=" ",orderNum="1")
	private String name;
	
	@Column(name="age")
	@Excel(name=" ",orderNum="2")
	private int age;
	
	@Column(name="hobby")
	@Excel(name=" ",orderNum="3")
	private String hobby;
	
	public User(){
		
	}
	public User(int id, String name, int age, String hobby) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
		this.hobby = hobby;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getHobby() {
		return hobby;
	}
	public void setHobby(String hobby) {
		this.hobby = hobby;
	}
	
	 @Override
	    public String toString() {
	        return "userExcel{" +
	                "id='" + id + '\'' +
	                ", name=" + name +
	                ", age=" + age +
	                ", hobby=" + hobby +
	                '}';
	    }
	
}


설정이 완료되면 controller의 가져오기 내보내기 함수를 작성합니다.


@GetMapping("/exportInfo")
    public void export(HttpServletResponse response) {
        System.out.println(1+"*/*/*/*/*/*/*/*/*/*/*/*");
//         
        List list = (List) userService.showAll();
//          
		ExcelUtiles.exportExcel(list, " ", " ", User.class, " .xls", response);
 
    }
	
	@PostMapping("/importInfo")
    public String importInfo(@RequestParam("file") MultipartFile file) {
		System.out.println(" ");
        ImportParams importParams = new ImportParams();
        //  
        importParams.setHeadRows(1);
        importParams.setTitleRows(1);
 
        //  
        importParams.setNeedVerfiy(true);
 
        try {
            ExcelImportResult result = ExcelImportUtil.importExcelMore(file.getInputStream(), User.class,
                    importParams);
 
            List successList = result.getList();
            for (User user : successList) {
              System.out.println(user);
              boolean result1 = userService.selectById(user);
              if(result1) {
            	  userService.updateUserInfo(user);
              }else {
            	  userService.insertUserInfo(user);
              }
              System.out.println(result1);
            }
        } catch (IOException e) {
        } catch (Exception e) {
        }
        return "showIn";
    }
    

그리고 jsp 파일에서 이 두 함수를 호출하여 실행할 수 있습니다. Excel을 가져오는 함수에서 먼저 데이터베이스에서 이 id가 존재하는지 여부를 찾고, 존재하지 않으면 데이터베이스 업데이트를 하고, 존재하지 않으면 이 id를 삽입한user가 데이터베이스에 들어갑니다.

좋은 웹페이지 즐겨찾기