첫번째 예제
엑셀 파일을 읽어들이는 API : POI, commons-codec, commons-collections 다운로드 받자
임의의 엑셀 데이터를 만들자.
bookList.xlsx
ExcelVO를 만들어서 엑셀에서 불러온다음에 하나로 묶을 때 가지고 와서
ArrayList에 첫번째 VO, 두번째 VO, 세번째 VO 등등...
최종 ArrayList에다가 책 정보를 담는 것.
담아져 있는 엑셀 정보를 화면에다가 출력하는 과정.
POI는 마이크로소프트에서 만든 데이터들의 포멧 파일들을 핸들링 할 수 있는 API
※ 실습을 해본 결과 API를 더 다운받아야 한다.
원래 코드는 FileInputStream으로 읽은 파일을 HSSFWorkbook 객체를 이용하여 메모리에다가 올리는 식으로 구성되었다.
하지만 여기서 문제점은 Excel이 2007 이상인 경우 이 방법이 통하지 않는다는 점이였다.
XSSFWorkbook 객체를 이용해야 한다. 즉, 새로운 API를 더 다운받아야 한다는 것.
다운 받지 않으면 에러 메시지가 뜬다.
ClassNotFoundException: org.apache.xmlbeans.XmlObject
그래서 추가할 API는
BuildPath를 통해 Add External JARS를 눌러 다운 받은 jar 파일을 등록해준다.
public class Project03_A {
public static void main(String[] args) {
String fileName="bookList.xlsx";
List<ExcelVO>data=new ArrayList<ExcelVO>();
try(FileInputStream fis=new FileInputStream(fileName)){
XSSFWorkbook workbook=new XSSFWorkbook(fis);
XSSFSheet sheet=workbook.getSheetAt(0);
Iterator rows=sheet.rowIterator();
String[]imsi=new String[5];
rows.next();
while(rows.hasNext()) {
XSSFRow row=(XSSFRow)rows.next();
Iterator cells=row.cellIterator();
int i=0;
while(cells.hasNext()) {
XSSFCell cell=(XSSFCell)cells.next();
imsi[i]=cell.toString();
i++;
}
ExcelVO vo=new ExcelVO(imsi[0], imsi[1], imsi[2], imsi[3], imsi[4]);
data.add(vo);
}
}catch(Exception e) {
e.printStackTrace();
}
showExcelData(data);
}
private static void showExcelData(List<ExcelVO> data) {
for(ExcelVO vo:data) {
System.out.println(vo);
}
}
}
package kr.inflearn;
public class ExcelVO {
private String title;
private String author;
private String company;
private String isbn;
private String imageUrl;
public ExcelVO(){}
public ExcelVO(String title, String author, String company, String isbn, String imageUrl) {
super();
this.title = title;
this.author = author;
this.company = company;
this.isbn = isbn;
this.imageUrl = imageUrl;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
@Override
public String toString() {
return "ExcelVO [title=" + title + ", author=" + author + ", company=" + company + ", isbn=" + isbn
+ ", imageUrl=" + imageUrl + "]";
}
}
'자바TPC 프로젝트' 카테고리의 다른 글
P3. Excel에 cell의 DataType 알아보기(3) (0) | 2022.02.06 |
---|---|
P3 Excel에 이미지 저장하기(2) (0) | 2022.02.06 |
P2 Jsoup API를 이용하여 웹 페이지 Crawling 하기(2) (0) | 2022.02.04 |
P2 Jsoup API를 이용하여 웹 페이지 Crawling 하기(1) (0) | 2022.02.04 |
P1. 주소를 입력하면 위도와 경도를 추출하는 프로그래밍(3) (0) | 2022.02.04 |