전자정부프레임워크를 이용한 프로젝트에서 엑셀파일의 데이터를 가져오는 코드
여기서 사용한 모델 클래스는 임시로 작성한 코드이며, 사용할 모델에 맞게 수정이 필요하다.
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; | |
| } | |
| } |
| // 단순 참고용 모델 클래스 | |
| 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; | |
| } | |
| } |