엑셀 업로드 리스트 출력을 위한 참고.. jxl 는 이전글 참고.. [ http://blog.daum.net/zelkun/111 ]
이전에 구현한 jxl 은 xls 파일만 읽어오니..
범용으로 xlsx도 읽을수 있도록 POI를 사용..(xls, xlsx 가능)
- 보안문서를 읽을수 없어(해제 해야함..) CSV를 지원해달라는 요청이 들어옴..
CVS 참고 [ http://my1over.blog.me/120129054480 ]
row와 cell 개수를 알아와야되는데.. 잘몰라서 그냥 tmp하나만들어서 읽어오게함.
지원을 안하는건지...
readNext를 사용해서 cell 개수를 읽어오고 List로 만들어서 row를 읽어옴
구현하고 서버에 올리니 한글이 깨져서.. 소스가 수정됨.
Iterator 를 사용해서 list에서 한줄씩 읽어오게 했는데..
cell 10개 읽고 다음줄로 넘어가는 현상이 발생... 아래 소스엔 변경된거라 멀쩡하게 잘나옴..
String excel_name = "sample.xls"
String type = excel_name.substring(excel_name.lastIndexOf(".")+1);
//파일 확장자에 따라서 Reader 를 선택. POI는 xls도 읽지만.. 만들어논거니 그냥 jxl로 읽게함..
File excelFile = new File(filePath + excel_name);
String[][] data = null;
if(type.equals("csv")){
data = ExcelRederUtil.simpleExcelReadCsv(excelFile);
} else if(type.equals("xls")){
data = ExcelRederUtil.simpleExcelReadJxl(excelFile);
} else if(type.equals("xlsx")){
data = ExcelRederUtil.simpleExcelReadPoi(excelFile);
}
/* ExcelRederUtil */
package com.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
/* jxl 사용 *
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
/* Poi 사용 *
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
/* excelReader */
public class ExcelRederUtil {
private static final Logger log = Logger.getLogger(ExcelRederUtil.class);
public final static String[][] simpleExcelReadCsv(File targetFile) throws Exception{
String[][] data = null;
FileInputStream csvFile = new FileInputStream(targetFile);
InputStreamReader readFile = new InputStreamReader(csvFile, "EUC-KR");
//한글처리 Local에선 파일로 읽어도 한글이 잘 나왔는데 서버에 올리니 서버 언어설정 //을 따라가는지 UTF-8 로 변해서 한글이 깨짐... EUC-KR로 고정함.
CSVReader reader = new CSVReader(readFile);
CSVReader tmpReader = new CSVReader(new FileReader(targetFile));
try{
int colCount = tmpReader.readNext().length; //cell의 개수
List tmpList = tmpReader.readAll(); //row개수를 알기위함
//colCount보다 먼저 선언하면 readNext를 할수 없다.. 전부 읽어오기 때문인듯..
int rowCount = tmpList.size()+1; //row 개수
data = new String[rowCount][colCount];
int idx = 0;
String[] nextLine;
while ( (nextLine = reader.readNext()) != null ){
int i = 0;
for ( String str : nextLine ){
data[idx][i] = str;
// System.out.println("idx : " + idx + " i : " + i +" data : " + str);
i++;
}
idx++;
}
/*
//데이터 검증 테스트
for (int r = 0; r < data.length; r++) {
for (int c = 0; c < data[0].length; c++) {
System.out.print( r + " : " + c + " : " + data[r][c] + " ");
}
System.out.println();
}
*/
} catch (Exception e) {
System.out.println("CSVReader error : " + e.getMessage());
}
return data;
}
/* Poi 사용 */
public final static String[][] simpleExcelReadPoi(File targetFile) throws Exception{
org.apache.poi.ss.usermodel.Workbook workbook = null;
org.apache.poi.ss.usermodel.Sheet sheet = null;
org.apache.poi.ss.usermodel.Row row = null;
org.apache.poi.ss.usermodel.Cell cell = null;
String[][] data = null;
try {
workbook = org.apache.poi.ss.usermodel.WorkbookFactory.create(targetFile);
org.apache.poi.ss.usermodel.FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
sheet = workbook.getSheetAt(0);
int rows = sheet.getLastRowNum();
int cells = sheet.getRow(0).getLastCellNum();
if(rows > 200){ rows = 200; }
data = new String[rows][cells];
int idx = 0;
for(Iterator all = sheet.iterator(); all.hasNext(); ){
org.apache.poi.ss.usermodel.Row ds = (org.apache.poi.ss.usermodel.Row)all.next();
for(int i = 0; i< cells; i++){
cell = ds.getCell(i);
switch(cell.getCellType()){
case 0: //Cell.CELL_TYPE_NUMERIC :
if(org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)){
data[idx][i] = cell.getDateCellValue().toString();
} else{
data[idx][i] = Integer.toString((int) cell.getNumericCellValue());
}
break;
case 1: //Cell.CELL_TYPE_STRING :
data[idx][i] = cell.getRichStringCellValue().getString();
break;
case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_BOOLEAN :
data[idx][i] = cell.getBooleanCellValue()+"";
break;
case org.apache.poi.ss.usermodel.Cell.CELL_TYPE_FORMULA :
if(evaluator.evaluateFormulaCell(cell) == org.apache.poi.ss.usermodel.Cell.CELL_TYPE_NUMERIC){
if(org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)){
data[idx][i] = "";
} else{
Double value = new Double(cell.getNumericCellValue());
if((double)value.longValue() == value.doubleValue()){
data[idx][i] = data[idx][i] = Long.toString(value.longValue());
} else{
data[idx][i] = data[idx][i] = value.toString();
}
}
} else if(evaluator.evaluateFormulaCell(cell) == org.apache.poi.ss.usermodel.Cell.CELL_TYPE_STRING){
data[idx][i] = cell.getStringCellValue();
} else if(evaluator.evaluateFormulaCell(cell) == org.apache.poi.ss.usermodel.Cell.CELL_TYPE_BOOLEAN){
data[idx][i] = new Boolean(cell.getBooleanCellValue()).toString();
} else {
data[idx][i] = cell.toString();
}
break;
default:
}
}
if(idx == 200){
break;
}
idx++;
}
/*
// 데이터 검증 테스트
for (int r = 0; r < data.length; r++) {
for (int c = 0; c < data[0].length; c++) {
System.out.println("index : " + r + " : " + data[r][c]);
}
}
*/
}catch(Exception e){
System.out.println("ExcelReadPoi error : " + e.getMessage());
}
return data;
}
/* JXL을 사용한 excelRead */
public final static String[][] simpleExcelReadJxl(File targetFile) throws Exception {
jxl.Workbook workbook = null;
jxl.Sheet sheet = null;
String[][] data = null;
try {
workbook = jxl.Workbook.getWorkbook(targetFile); // 존재하는 엑셀파일 경로를 지정
sheet = workbook.getSheet(0); // 첫번째 시트를 지정합니다.
int rowCount = sheet.getRows(); // 총 로우수를 가져옵니다.
int colCount = sheet.getColumns(); // 총 열의 수를 가져옵니다.
if (rowCount <= 0) {
throw new Exception("Read 할 데이터가 엑셀에 존재하지 않습니다.");
}
data = new String[rowCount][colCount];
// 엑셀데이터를 배열에 저장
for (int i = 0; i < rowCount; i++) {
for (int k = 0; k < colCount; k++) {
jxl.Cell cell = sheet.getCell(k, i); // 해당위치의 셀을 가져오는 부분입니다.
if (cell == null)
continue;
data[i][k] = cell.getContents(); // 가져온 셀의 실제 콘텐츠 즉
// 데이터(문자열)를 가져오는 부분입니다.
}
}
/*
// 데이터 검증 테스트
for (int r = 0; r < data.length; r++) {
for (int c = 0; c < data[0].length; c++) {
System.out.print(data[r][c] + " ");
}
System.out.println();
}
*/
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
try {
if (workbook != null)
workbook.close();
} catch (Exception e) {
}
}
return data;
}
/**/
}
/* CSV */
[http://opencsv.sourceforge.net/]
/* POI */
poi-ooxml-schemas-3.8-20120326.jar
'JAVA > 라이브러리' 카테고리의 다른 글
Java HTML parser, Jsoup로 원하는 값 얻어내기 - Ajax (0) | 2017.12.11 |
---|---|
Java HTML parser, Jsoup로 원하는 값 얻어내기 - 로그인 (0) | 2017.12.11 |
Java HTML parser, Jsoup로 원하는 값 얻어내기 - 기본 (0) | 2017.12.11 |
롬복(Lombok)의 어노테이션들 - (SneakyThrows, Synchronized, Log) (0) | 2017.12.11 |
롬복(Lombok)의 어노테이션들 - (EqaulsAndHashCode, XArgsConstructor, Data, Value, Builder) (0) | 2017.12.11 |
롬복(Lombok)의 어노테이션들 - (val/var, NonNull, Cleanup, ToString) (0) | 2017.12.11 |
HttpComponent 참조 블로그 (0) | 2015.08.24 |
[JAVA] excel 참조 블로그 (0) | 2014.10.16 |