Java
자바 엑셀파일 읽기 - java read excel, xlsx, xls
수유산장
2019. 8. 14. 16:01
1. 엑셀 파일 형식
번호 |
이름 |
생년월일 |
1 |
홍길동 |
2001-01-31 |
2 |
홍길순 |
2010-02-28 |
3 |
홍길자 |
2019-05-05 |
위와 같이 학생 목록의 엑셀을 읽어서
학생 List를 만들것이므로 우선 학생 DTO를 만든다.
2. DTO 생성
import java.util.Date;
public class StudentDTO {
Integer id; //번호
String name; //이름
Date birthDate; //생년월일
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
}
3. pom.xml 에 dependency 추가
메이븐 프로젝트인 경우 디펜던시를 추가한다.
다른 형식의 프로젝트인 경우 해당 프로젝트에 맞추어 라이브러리를 임포트한다.
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
</dependency>
4. 엑셀 파일 읽기
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.EncryptedDocumentException;
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.ss.usermodel.WorkbookFactory;
public class ExcelImport {
public static void main( String[] args ) throws EncryptedDocumentException, IOException
{
List<StudentDTO> studnetList = getStudentList();
for (StudentDTO studentDTO : studnetList) {
System.out.println(studentDTO.getId() + ", " + studentDTO.getName() + ", " + studentDTO.getBirthDate());
}
}
public static List<StudentDTO> getStudentList() throws EncryptedDocumentException, IOException {
List<StudentDTO> studentList = new ArrayList<StudentDTO>();
// 웹상에서 업로드 되어 MultipartFile인 경우 바로 InputStream으로 변경하여 사용.
// InputStream inputStream = new ByteArrayInputStream(file.getBytes());
String filePath = "D:\\student.xlsx"; // xlsx 형식
// String filePath = "D:\\student.xls"; // xls 형식
InputStream inputStream = new FileInputStream(filePath);
// 엑셀 로드
Workbook workbook = WorkbookFactory.create(inputStream);
// 시트 로드 0, 첫번째 시트 로드
Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowItr = sheet.iterator();
// 행만큼 반복
while(rowItr.hasNext()) {
StudentDTO student = new StudentDTO();
Row row = rowItr.next();
// 첫번재 행이 해더인 경우 스킵, 2번째 행부터 data 로드
if(row.getRowNum() == 0) {
continue;
}
Iterator<Cell> cellItr = row.cellIterator();
// 한행이 한열씩 읽기 (셀 읽기)
while(cellItr.hasNext()) {
Cell cell = cellItr.next();
int index = cell.getColumnIndex();
switch(index) {
case 0: // 번호
student.setId(((Double)getValueFromCell(cell)).intValue());
// 셀이 숫자형인 경우 Double형으로 변환 후 int형으로 변환
break;
case 1: // 성명
student.setName((String)getValueFromCell(cell));
break;
case 2: // 생년월일
student.setBirthDate((Date)getValueFromCell(cell));
break;
}
}
studentList.add(student);
}
return studentList;
}
// 셀서식에 맞게 값 읽기
private static Object getValueFromCell(Cell cell) {
switch(cell.getCellType()) {
case STRING:
return cell.getStringCellValue();
case BOOLEAN:
return cell.getBooleanCellValue();
case NUMERIC:
if(DateUtil.isCellDateFormatted(cell)) {
return cell.getDateCellValue();
}
return cell.getNumericCellValue();
case FORMULA:
return cell.getCellFormula();
case BLANK:
return "";
default:
return "";
}
}
}
기존에 xls, xlsx 파일을 구분하지 않고 읽는다.
웹시스템에서는 주로 Multipart 형식으로 파일을 업로드 하여 엑셀을 읽으므로
서버에 저장없이 메모리에서 처리가 가능하다.
InputStream을 바로 생성하여 엑셀 파일을 읽으면 된다.