본문 바로가기
개발관련/JAVA

JAVA) apache poi, 엑셀 파일 생성 및 다운로드 하기

by joa-yo 2021. 6. 26.
반응형

안녕하세요. 이번 프로젝트에서는 유난히도 엑셀관련한 작업을 많이 하게 되었습니다. 그래서 준비한 포스팅! 이번에는 엑셀로 데이터를 출력하거나 엑셀 데이터를 읽을 때 사용할 수 있는 라이브러리인 poi에 대해 포스팅 하는 시간을 가져보겠습니다!

 

자세한 사항은 apache poi 공식사이트를 확인해주세요.

 

Apache POI - the Java API for Microsoft Documents

Apache POI - the Java API for Microsoft Documents Project News 20 January 2021 - POI 5.0.0 available The Apache POI team is pleased to announce the release of 5.0.0. This release features full JPMS support, updated ECMA-376 OOXML schemas, various rendering

poi.apache.org

API 문서 https://poi.apache.org/apidocs/index.html
POI란 무엇인가? https://poi.apache.org/components/spreadsheet/index.html
POI 퀵가이드 https://poi.apache.org/components/spreadsheet/quick-guide.html

 

포이는 Workbook을 기준으로 HSSF, XSSF, SXSSF로 나눌 수 있습니다. HSSF는 2007하위 버전인 .xls파일에서만 동작 가능하지만, XSSF는 2007이상 버전인 .xlsx파일에서도 동작 가능합니다. SXSSF는 대용량 엑셀 파일을 출력할 때 사용할 수 있습니다.

 

여담이지만 저의 경우, .xls 파일과 .xlsx파일을 받을 일이 있었는데 이 경우에는 파일 확장자를 확인한 뒤 맞는 workbook으로 지정해주니 해결됐습니다.

 

 

 

 

 


 

 

 

엑셀 구성 단위

WorkBook > Sheet > Row > Cell

 

 

Row는 행, Cell은 한칸을 의미하는데 이를 관리하기위 하나의 면이 Sheet입니다. Sheet도 여러 개가 생성 될 수 있는데 이를 관리하기 위한 것이 WorkBook이며 엑셀파일을 의미합니다.

 

 

 

 

 


 

 

 

 

셀에 값 설정하기

0번째행 0번째열에 데이터 '1'을 부여하는 과정은 아래와 같습니다.

//엑셀파일 생성
Workbook wb = new HSSFWorkbook();

//시트 생성 (이름은 "new sheet"라고 부여됨)
Sheet sheet = wb.createSheet("new sheet");

//0번째 행 생성
Row row = sheet.createRow(0);

//1번째 셀 생성
Cell cell = row.createCell(0);

//해당 셀에 값 지정
cell.setCellValue(1);

 

 

 

 

 


 

 

 

 

셀에 스타일 지정하기

public static void main(String[] args) throws Exception {
    Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
    Sheet sheet = wb.createSheet();
    Row row = sheet.createRow(2);
    row.setHeightInPoints(30);
    createCell(wb, row, 0, HorizontalAlignment.CENTER, VerticalAlignment.BOTTOM);
    createCell(wb, row, 1, HorizontalAlignment.CENTER_SELECTION, VerticalAlignment.BOTTOM);
    createCell(wb, row, 2, HorizontalAlignment.FILL, VerticalAlignment.CENTER);
    createCell(wb, row, 3, HorizontalAlignment.GENERAL, VerticalAlignment.CENTER);
    createCell(wb, row, 4, HorizontalAlignment.JUSTIFY, VerticalAlignment.JUSTIFY);
    createCell(wb, row, 5, HorizontalAlignment.LEFT, VerticalAlignment.TOP);
    createCell(wb, row, 6, HorizontalAlignment.RIGHT, VerticalAlignment.TOP);
    // Write the output to a file
    try (OutputStream fileOut = new FileOutputStream("xssf-align.xlsx")) {
        wb.write(fileOut);
    }
    wb.close();
}
/**
 * Creates a cell and aligns it a certain way.
 *
 * @param wb     the workbook
 * @param row    the row to create the cell in
 * @param column the column number to create the cell in
 * @param halign the horizontal alignment for the cell.
 * @param valign the vertical alignment for the cell.
 */
private static void createCell(Workbook wb, Row row, int column, HorizontalAlignment halign, VerticalAlignment valign) {
    Cell cell = row.createCell(column);
    cell.setCellValue("Align It");
    CellStyle cellStyle = wb.createCellStyle();
    cellStyle.setAlignment(halign);
    cellStyle.setVerticalAlignment(valign);
    cell.setCellStyle(cellStyle);
}

코드 출처 : apache poi 공식 홈페이지

위의 코드를 보면 객체 'CellStyle'을 만들어 정렬값을 셋팅하고 있습니다. CellStyle은 Row또는 Cell에도 지정해줄 수 있는데, 정렬 값 이외에도 어떤 값들을 설정할 수 있는지 알아보겠습니다.

 


 'CellStyle'로 아래와 같은 '속성'들을 정의할 수 있습니다.
  • 가로정렬 지정 (HorizontalAliginment 활용)
  • 세로정렬 지정 (
  • 경계선 상,하,좌,우 각각 두께 설정(BorderStyle 활용)
  • 경계선 상,하,좌,우 각각 색상 설정(기본값 BLACK)
  • 데이터 형식 
  • 배경 채우기 지정
  • 배경색 지정
  • 전경색 지정
  • 폰트 스타일 지정
  • 셀 여백(indention) 지정
  • 락 지정
  • 자동줄바꿈여부 (wrapText)


    자세한 사항은 api문서 중 cellStyle을 확인해주세요( http://poi.apache.org/apidocs/5.0/org/apache/poi/ss/usermodel/CellStyle.html )

 

CellStyle에 cloneStyleFrom(CellStyle cellstyle)이라는 함수가 있는데, 이 함수는 스타일을 그대로 복사해오지만 속성값을 변경하는 경우 모두 초기화 되버리는 듯한 느낌이 있었다....

 

 

 

 

 


 

 

 

 

 

엑셀파일 응답 보내기

Workbook workbook = new XSSFWorkbook(); 
Sheet sheet = workbook.createSheet("데이터");

rowNum = 0;

createExcel(sheet, datas);

//엑셀파일로 다운받을 수 있도록 설정
String fileName = "fileName";
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", String.format("attachment;filename=%s.xlsx", fileName));

workbook.write(response.getOutputStream());
workbook.close();

Workbook은 response에 직접 엑셀 파일 내용을 출력합니다.  먼저 위의 코드와 같이 setContentType을 지정해주어 엑셀타입임을 지정합니다. setHeader는 다운로드시 파일명을 의미합니다. workbook은 response의 outputStream을 이용하여 응답데이터에 엑셀 내용을 출력하는데, close()하는 순간 바로 응답이 되어버립니다. 따라서 close후의 코드는 실행되지 않기 때문에 이전에 모든 작업을 마쳐주어야 한다는 점에 유의해야 합니다.

 

 

 

 

 


 


추 천 포 스 트

 

 

https://joalog.tistory.com/184

 

반응형

댓글