메뉴 건너뛰기

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
번호 제목 날짜 조회 수
» ExcelUtil 2021.03.09 330
42 서버로부터 메시지 받아서 팝업 띄우기 (1. ModelAndView 이용) file 2021.03.09 574
41 Spring source 배포 및 Tomcat Server 셋팅 2019.03.05 1345
40 form에서 enctype="multipart/form-data"로 보낸 데이터를 request로 받기 2019.03.05 978
39 JAVA에서 alert창 띄우기 2019.03.05 1588
38 JSTL 숫자 포맷 맞추기 (<fmt:formatNumber> 사용 예제) 2019.03.05 1182
37 JSTL을 이용하여 합계 구하기 2019.03.05 1066
36 forEach문은 아래와 같이 활용한다. 2019.03.05 912
35 [JSTL core] [c:forEach] varStatus를 활용한 변수 2019.03.05 1048
34 전자정부표준프레임워크 파일 업로드 크기 설정(feat. MaxUploadSizeExceededException) file 2019.02.28 1101
33 @SessionAttributes와 SessionStatus 사용하기(세션에 모델 객체 저장) file 2019.02.28 1187
32 스프링프레임워크 <form:form> 태그 사용법 file 2019.02.28 3514
31 JSP에서 지시자(Directive) 또는 태그라이브러리에 의한 공백 라인을 제거하는 방법 file 2019.02.28 799
30 <c:url> 태그 사용법 file 2019.02.28 4324
29 JSTL - <c:if>, <c:choose> 태그 사용법 2019.02.28 2218
28 이클립스(Eclipse) 한글 언어팩 설치. Babel 프로젝트 file 2018.12.07 1199
27 이클립스(Eclipse) 소스 일괄 수정 file 2018.12.07 1097
26 전자정부프레임워크 설치 및 실행 file 2018.12.07 1381
25 JSP에서 지시자(Directive) 또는 태그라이브러리에 의한 공백 라인을 제거하는 방법 file 2018.12.06 1276
24 스프링프레임워크 <form:form> 태그 사용법 file 2018.12.06 1182
Board Pagination Prev 1 2 3 Next
/ 3

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

© k2s0o1d4e0s2i1g5n. All Rights Reserved