메뉴 건너뛰기

2021.03.09 13:05

ExcelUtil

조회 수 330 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

전자정부프레임워크를 이용한 프로젝트에서 엑셀파일의 데이터를 가져오는 코드

 

여기서 사용한 모델 클래스는 임시로 작성한 코드이며, 사용할 모델에 맞게 수정이 필요하다.

 

cell의 데이터 타입을 구분하는 코드 중 Cell.CELL_TYPE_NUMERIC 이후의 코드는 엑셀 데이터의 날짜값을 정상적으로 불러오지 못하는 문제가 있어서 수정중이다.

 

 

  import java.io.File;
  import java.io.FileInputStream;
  import java.io.FileOutputStream;
  import java.text.SimpleDateFormat;
  import java.util.ArrayList;
  import java.util.Date;
   
  import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  import org.apache.poi.ss.usermodel.Cell;
  import org.apache.poi.ss.usermodel.DateUtil;
  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.web.multipart.MultipartFile;
   
  public class ExcelUtil {
  @SuppressWarnings("unchecked")
  // 엑셀 파일로부터 데이터를 추출한 뒤 ArrayList로 반환하는 함수
  public static Object getExcelData(File excelFile, String modelType) {
  Workbook workbook = null;
  Sheet workSheet = null;
  Row row = null;
  String cellData = "";
  Date cellDate = new Date();
  boolean cellBooleanValue = false;
  Cell cell = null;
  Object returnObject = null;
  Object tempObject = null;
   
  // modelType에 따라서 반환되는 returnObject의 타입을 변경해준다.
  if (modelType.equals("YourModelClassName"))
  returnObject = new ArrayList<YourModelClassName>();
   
  FileInputStream fileInputStream = null;
  SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   
  try {
  // set Workbook
  fileInputStream = new FileInputStream(excelFile);
  // MS office 2007 이상 버전의 엑셀 파일의 경우에는 XSSFWorkbook으로 초기화해줘야 한다.
  if (excelFile.getName().toLowerCase().endsWith("xlsx"))
  workbook = new XSSFWorkbook(fileInputStream);
  // office 2003까지 지원하는 형식의 엑셀파일은 HSSFWorkbook으로 초기화한다.
  else
  workbook = new HSSFWorkbook(fileInputStream);
   
  workSheet = workbook.getSheetAt(0);
  int rowSize = workSheet.getLastRowNum() + 1;
   
  //첫 번째 줄은 일반적으로 컬럼의 이름이 들어가기 때문에 생략한다.
  for (int i = 1; i < rowSize; i++) {
  row = workSheet.getRow(i);
  cellData = "";
  cellDate = new Date();
  cellBooleanValue = false;
   
  if (modelType.equals("YourModelClassName"))
  tempObject = new YourModelClassName();
   
  for (int j = 0; j < row.getLastCellNum(); j++) {
  cell = row.getCell(j);
   
  if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) {
  switch (cell.getCellType()) {
  case Cell.CELL_TYPE_STRING:
  cellData = cell.getStringCellValue();
  break;
  // 들어있는 데이터가 날짜 형식인 경우에도 CELL_TYPE_NUMERIC이 반환된다.
  // 숫자 데이터와 날짜 데이터를 구분하는 코드는 미구현
  case Cell.CELL_TYPE_NUMERIC:
  System.out.println(DateUtil.isCellDateFormatted(cell));
  cellDate = DateUtil.getJavaDate(cell.getNumericCellValue());
  break;
   
  case Cell.CELL_TYPE_BOOLEAN:
  cellBooleanValue = cell.getBooleanCellValue();
  break;
  }
  }
   
  if (modelType.equals("YourModelClassName")) {
  // 모델 클레스에 맞게 tempObject 객체에 값을 넣어준다.
  // 순서는 불러온 엑셀 시트의 컬의 순서이다.
  switch (j) {
  case 0:
  ((YourModelClassName) tempObject).setName(cellData);
  break;
  case 1:
  ((YourModelClassName) tempObject).setDate(cellDate);
  break;
  case 2:
  ((YourModelClassName) tempObject).setIstrue(cellBooleanValue);
  break;
  }
  }
  }
  if (modelType.equals("YourModelClassName")) {
  ((ArrayList<YourModelClassName>) returnObject).add((YourModelClassName) tempObject);
  }
  }
   
  } catch (Exception e) {
  e.printStackTrace();
  }
   
  return returnObject;
  }
   
  // MultipartFile을 File 객체로 변환해주는 함수
  public static File changeMultipartFileToFile(MultipartFile multipartFile) {
  File convertFile = new File(multipartFile.getOriginalFilename());
  try {
  convertFile.createNewFile();
  FileOutputStream fileOutputStream = new FileOutputStream(convertFile);
  fileOutputStream.write(multipartFile.getBytes());
  fileOutputStream.close();
  return convertFile;
  } catch (Exception e) {
  e.printStackTrace();
  return null;
  }
  }
   
  // 엑셀파일 확장자를 검사하는 함수
  public static boolean checkExcelTypeWithName(String fileName) {
  String[] excelFileType = { "xlsx", "xlsm", "xlsb", "xltx", "xltm", "xls", "xlt", "csv" };
   
  for (String typeName : excelFileType) {
  if (fileName.toLowerCase().endsWith(typeName)) {
  return true;
  }
  }
  return false;
  }
  }
view rawExcelUtil.java hosted with ❤ by GitHub

 

  // 단순 참고용 모델 클래스
  class YourModelClassName {
  private String name;
  private Date date;
  private boolean istrue;
   
  public String getName() {
  return name;
  }
   
  public void setName(String name) {
  this.name = name;
  }
   
  public Date getDate() {
  return date;
  }
   
  public void setDate(Date date) {
  this.date = date;
  }
   
  public boolean isIstrue() {
  return istrue;
  }
   
  public void setIstrue(boolean istrue) {
  this.istrue = istrue;
  }
  }

 

 


List of Articles
번호 제목 날짜 조회 수
43 HTMLTagFilter ? 2016.09.21 7747
42 로그인 체크 인터셉터 사용 (AuthenticInterceptor) 2016.09.21 6674
41 message 사용을 위한 설정 2016.09.21 6550
40 getFileMap() 메소드를 이용한 파일 업로드 기능 구현하기 2016.09.21 6190
39 getFileNames() 메소드를 이용한 파일 업로드 기능 구현하기 2016.09.21 5802
38 공통코드관리 2016.09.21 5760
37 스프링 CKEditor 적용 - 에디터 2018.06.12 5569
36 전자정부 프레임워크(egov framework) 설치하기(1) file 2017.09.12 5296
35 Aspect 어노테이션 사용을 위한 설정. file 2016.08.18 5019
34 개발자로서 기본 구성합니다. file 2016.08.18 4937
33 spring ckeditor 파일업로드 예제 (file upload) file 2018.06.12 4513
32 <c:url> 태그 사용법 file 2019.02.28 4324
31 Spring Security의 동작 방법 file 2018.06.21 4263
30 전자정부 프레임워크(eGovframe) 동적 웹프로젝트 시작하기(2) file 2017.09.12 4165
29 java.lang.NoClassDefFoundError: org/springframework/dao/support/PersistenceExceptionTranslator 2016.09.21 4160
28 "알 수 없는 오류가 발생하였습니다." 라는 에러 메시지가 발생했을 때 대처법 2018.06.12 4137
27 전자정부프레임워크 구조 파악하기 file 2018.06.02 4117
26 스프링프레임워크 <form:form> 태그 사용법 file 2019.02.28 3514
25 CKEditor 사용 및 파일 업로드 적용 2018.06.12 3165
24 전자정부프레임워크 사용 중 중복 저장 방지 (새로고침 혹은 뒤로가기시) 2018.06.12 3053
Board Pagination Prev 1 2 3 Next
/ 3

하단 정보를 입력할 수 있습니다

© k2s0o1d4e0s2i1g5n. All Rights Reserved