메뉴 건너뛰기

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;
  }
  }

 

 


  1. No Image 05Mar
    by
    2019/03/05 Views 1048 

    [JSTL core] [c:forEach] varStatus를 활용한 변수

  2. No Image 05Mar
    by
    2019/03/05 Views 1346 

    Spring source 배포 및 Tomcat Server 셋팅

  3. Spring Security의 동작 방법

  4. spring ckeditor 파일업로드 예제 (file upload)

  5. No Image 21Sep
    by
    2016/09/21 Views 6561 

    message 사용을 위한 설정

  6. No Image 05Mar
    by
    2019/03/05 Views 1066 

    JSTL을 이용하여 합계 구하기

  7. No Image 05Mar
    by
    2019/03/05 Views 1182 

    JSTL 숫자 포맷 맞추기 (<fmt:formatNumber> 사용 예제)

  8. No Image 28Feb
    by
    2019/02/28 Views 2218 

    JSTL - <c:if>, <c:choose> 태그 사용법

  9. JSP에서 지시자(Directive) 또는 태그라이브러리에 의한 공백 라인을 제거하는 방법

  10. JSP에서 지시자(Directive) 또는 태그라이브러리에 의한 공백 라인을 제거하는 방법

  11. No Image 05Mar
    by
    2019/03/05 Views 1588 

    JAVA에서 alert창 띄우기

  12. No Image 21Sep
    by
    2016/09/21 Views 4162 

    java.lang.NoClassDefFoundError: org/springframework/dao/support/PersistenceExceptionTranslator

  13. No Image 21Sep
    by
    2016/09/21 Views 7757 

    HTMLTagFilter ?

  14. No Image 21Sep
    by
    2016/09/21 Views 5802 

    getFileNames() 메소드를 이용한 파일 업로드 기능 구현하기

  15. No Image 21Sep
    by
    2016/09/21 Views 6190 

    getFileMap() 메소드를 이용한 파일 업로드 기능 구현하기

  16. No Image 05Mar
    by
    2019/03/05 Views 980 

    form에서 enctype="multipart/form-data"로 보낸 데이터를 request로 받기

  17. No Image 05Mar
    by
    2019/03/05 Views 916 

    forEach문은 아래와 같이 활용한다.

  18. No Image 09Mar
    by 조쉬
    2021/03/09 Views 330 

    ExcelUtil

  19. No Image 12Jun
    by
    2018/06/12 Views 3165 

    CKEditor 사용 및 파일 업로드 적용

  20. Aspect 어노테이션 사용을 위한 설정.

Board Pagination Prev 1 2 3 Next
/ 3

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

© k2s0o1d4e0s2i1g5n. All Rights Reserved