자바의 JXL 라이브러리를 활용하여 엑셀파일을 읽은 후 ArrayList 리턴받기
※ 참고사항
공개된 JXL 라이브러리는 자바 1.4 버전에 컴파일된 듯 하다. 버전이 맞지않아 오류가 발생할 수 있으니 주의하자.
서버에 업로드된 엑셀파일을 열어 HashMap 에 Cell을 담고 List 에 Row를 담아 리턴하는 소스이다.
※ 참고사항
공개된 JXL 라이브러리는 자바 1.4 버전에 컴파일된 듯 하다. 버전이 맞지않아 오류가 발생할 수 있으니 주의하자.
서버에 업로드된 엑셀파일을 열어 HashMap 에 Cell을 담고 List 에 Row를 담아 리턴하는 소스이다.
ExcelUtils.java
/**
* @class ExcelUtils
* @brief
*
* registered date 20100908
* programmed by Seok Kyun. Choi. 최석균
* http://syaku.tistory.com
*/
package com.syaku.util;
import java.util.*;
import java.io.File;
import jxl.*;
import org.apache.log4j.Logger;
public class ExcelUtils {
private static Logger log = Logger.getLogger(ExcelUtils.class);
public List xlsForList(String file_path) throws Exception {
File file = new File(file_path);
if (!file.exists()) {
throw new Exception("파일이 존재하지 않습니다.");
}
Workbook workbook = null;
Sheet sheet = null;
List list = new ArrayList();
try {
workbook = Workbook.getWorkbook(file);
sheet = workbook.getSheet(0);
int row = sheet.getRows();
int col = sheet.getColumns();
if(row <= 0) { throw new Exception("내용이 없습니다."); }
for(int i = 0; i < row ; i++) {
HashMap hm = new HashMap();
for(int o = 0; o < col ; o++) {
hm.put("COL"+o,sheet.getCell(o,i).getContents());
}
list.add(i,hm);
}
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
try {
if(workbook != null) { workbook.close(); }
} catch (Exception e) { }
}
return list;
}
}
예제소스
String excel_file = "/excel.jsp"; // 절대경로의 엑셀파일
ExcelUtils excel = new ExcelUtils();
List result = excel.xlsForList(excel_file);
for (int i =1; i < result.size(); i++) {
HashMap hm2 = (HashMap)result.get(i);
out.println(hm2.get("COL0"));
out.println(hm2.get("COL1"));
out.println(hm2.get("COL2"));
out.println(hm2.get("COL3"));
out.println(hm2.get("COL4"));
out.println(hm2.get("COL5"));
out.println(hm2.get("COL6"));
out.println(hm2.get("COL7"));
out.println(hm2.get("COL8"));
out.println(hm2.get("COL9"));
out.println(hm2.get("COL10"));
out.println(hm2.get("COL11"));
out.println(hm2.get("COL12"));
}