[JAVA] POI 라이브러리를 이용한 엑셀 파일 쓰기
POI 라이브러리를 통한 엑셀 파일 읽기
첫번째로 기억해야 하는 것은 엑셀 파일의 버전 별 코드가 달라진다는 점이다.
혹여 XLSX 확장자에 XLS 를 읽는 코드를 사용하였다면 콘솔 에러에 xssf instead of hssf 라는 말이 존재할 것이다.
* 내부 코드는 같은데 선언 할 때 변수가 달라진다(하단에 참고 링크 확인해주세요!).
구글링을 통한 대부분의 예제들은 한 개의 엑셀 파일을 읽거나 한 번만 작성한다..
내가 필요했던 기능은 원할 때 기존 엑셀 파일에 행을 추가해야했다.
엑셀 파일 저장을 했다가 다시 엑셀 파일을 연 후 행을 추가해야했다.
기본적인 로직 설명은 하겠지만 구체적인 로직 설명은 다른 블로그에 충분하니... 생략하겠다.
아래의 메소드는 엑셀파일 초기화 메소드이다(0행만 생성 후 저장).
!주의점 init 과정에서 0행만 초기화를 해주었다. 나중에 행을 추가할때 해당 라인을 생성(정의)해줘야한다.
그렇지않고 해당 셀을 읽을 시 NullPointException이 나타나 고생하게된다;;
* 인자로 넘겨주는 path는 저장할 파일 경로를 뜻한다.
public String writeExcelInit(String path) {
String excelName = "";
XSSFWorkbook workbook = new XSSFWorkbook(); //워크북 생성(xlsx 확장자 일때)
XSSFSheet sheet = workbook.createSheet(); //sheet 생성
XSSFRow row = sheet.createRow(0); //0행 생성
XSSFCell cell;
cell = row.createCell(0); //[0, 0] 공간 할당
cell.setCellValue("엑셀 상단 [0, 0]");
cell = row.createCell(1); //[0, 1] 공간 할당
cell.setCellValue("엑셀 상단 [0, 1]");
excelName = getCurrentTime() + ".xlsx";
String filePath = path + "\\" + excelName;
File file = new File(filePath);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
workbook.write(fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (workbook != null) {
workbook.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return excelName; //엑셀 파일 이름 반환.
}
기존의 엑셀파일에 추가로 행을 추가하는 메소드
아래 인자는 path = 파일경로 해당 xlsx까지, i = 행, hierarchy = 0열에 들어갈 값, lowCount = 1열에
들어갈 값
public void writeExcelLineCount(String path, int i, String hierarchy, int lowCount) throws IOException {
FileOutputStream outStream = null;
InputStream fis = null;
XSSFWorkbook workbook = null;
try {
fis = new FileInputStream(path); //*.xlsx 경로를 path에 넣어주면 됨
workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheetAt(0); //0번째 sheet 읽기
/* [중요]i행 생성 추가하려는 행이 선언(createRow)이 안되어있는데
아래와 같이 setCellValue를 시도한다면 NullPointException을 만나게된다.
*/
sheet.getRow(i).createCell(0).setCellValue(hierarchy); // [i, 0]에 값 넣음
sheet.getRow(i).createCell(1).setCellValue(String.valueOf(lowCount));
outStream = new FileOutputStream(path);
workbook.write(outStream) //기존 엑셀파일에 덮어씌우기
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException io) {
io.printStackTrace();
} finally {
if (workbook != null) {
workbook.close();
}
}
}
혹여.. 홈페이지에서 다운로드가 어려운 분들을 위해 POI 해당 라이브러리도 추가해놓겠다.
https://drive.google.com/file/d/1j6Ia2XsMdu-fumrCjkI9g7LwYBYFHPFT/view?usp=sharing
POI 다운로드
Binary Distribution 안에있는 poi-bin-3.17-20170915.zip 을 다운받으면된다.(20180220 기준)
http://poi.apache.org/download.html
참고 사이트
댓글
댓글 쓰기