Spring poi 엑셀 다운로드 - Spring poi egsel daunlodeu

jhhan의 블로그

Spring

Spring - Excel 파일 다운로드(간단)

jhhan000 2021. 1. 6. 22:37

이번 포스트는 spring으로 엑셀파일을 다운받는 방법입니다.

다른 포스트들은 너무 복잡하게 나와있는 것 같아서 최대한 간단하게 해봤습니다.

offbyone.tistory.com/250

참고한 블로그입니다.

먼저 간단한 스프링 프로젝트를 만듭니다.

프로젝트 설정 시 spring web과 thymeleaf를 추가해주시기 바랍니다.

저는 gradle로 진행했습니다. maven이어도 큰 문제는 없습니다.

Spring poi 엑셀 다운로드 - Spring poi egsel daunlodeu

프로젝트 구조입니다. -> 매우 간단합니다. ㅎㅎ

build.gradle 파일을 먼저 설정해 봅니다.

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'

    compile group: 'org.apache.poi', name: 'poi', version: '4.1.2'        // HSSFWorkbook 사용가능
    compile group: 'org.apache.poi', name: 'poi-ooxml', version: '4.1.2'  // XSSFWorkbook 사용가능
}

다른 부분은 건드리지 않고 dependencies만 추가합니다.

기존에 추가한 타임리프, 스프링 웹을 볼 수 있습니다.

밑에서 2개에 해당하는 org.apache.poi 부분을 추가하면 됩니다.

Maven의 경우에는 다음과 같이 추가합니다.

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>

다음으로 home.html 파일입니다.

간단히 진행하기 때문에 화면도 간단합니다.

<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div>
        <h2>Excel Download</h2>
        <form action="/excel/download" method="get">
            <button type="submit">Excel</button>
        </form>
    </div>
</body>
</html>

정말 간단합니다.

다른 부분은 바꾸셔도 되지만, <form> 태그 부분은 저런 방식으로 작성하셔야 합니다.

막상 적고 나니 타임리프를 사용하지도 않았네요.

나중에 활용하고 싶은 사람들은 잘 쓰면 될 것 같습니다.

이제 MainController 부분입니다. 가장 메인입니다. ㅋㅋㅋ

@Controller
public class MainController {

    @GetMapping("/")
    public String home() {
        return "home";
    }

    @GetMapping("/excel/download")
    public void excelDownload(HttpServletResponse response) throws IOException {
//        Workbook wb = new HSSFWorkbook();
        Workbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet("첫번째 시트");
        Row row = null;
        Cell cell = null;
        int rowNum = 0;

        // Header
        row = sheet.createRow(rowNum++);
        cell = row.createCell(0);
        cell.setCellValue("번호");
        cell = row.createCell(1);
        cell.setCellValue("이름");
        cell = row.createCell(2);
        cell.setCellValue("제목");

        // Body
        for (int i=0; i<3; i++) {
            row = sheet.createRow(rowNum++);
            cell = row.createCell(0);
            cell.setCellValue(i);
            cell = row.createCell(1);
            cell.setCellValue(i+"_name");
            cell = row.createCell(2);
            cell.setCellValue(i+"_title");
        }

        // 컨텐츠 타입과 파일명 지정
        response.setContentType("ms-vnd/excel");
//        response.setHeader("Content-Disposition", "attachment;filename=example.xls");
        response.setHeader("Content-Disposition", "attachment;filename=example.xlsx");

        // Excel File Output
        wb.write(response.getOutputStream());
        wb.close();
    }
}

간단하게 작성했기 때문에 코드 양도 굉장히 적습니다.

HSSFWorkbook & XSSFWorkbook -> 두 가지 중 하나를 선택해서 진행하면 됩니다.

  • xls 확장자를 가진 엑셀 파일 -> HSSFWorkbook
  • xlsx 확장자를 가진 엑셀 파일 -> XSSFWorkbook
  • 헤더의 경우 간단하게 하기 위해 3가지만 설정했습니다.
  • 바디의 경우 for문으로 반복해서 적게 했습니다.
  • 컨텐츠 타입과 파일명도 지정해줍니다.
  • 그리고 마지막으로 엑셀 파일을 저장합니다.

그리고 cell을 디자인 하는 것도 있지만,,,

그건 사치입니다. 과감히 생략했습니다.

다른 블로그를 통해 배울 수 있습니다...

지금 이 글은 간단하게 Excel 파일을 다운로드 할 수 있게 하는 것이니까요.

이제 스프링 프로젝트를 실행합니다. 그리고 localhost:8080으로 접속해보면...

Spring poi 엑셀 다운로드 - Spring poi egsel daunlodeu

굉장히 간단한 화면을 만날 수 있습니다... 꾸민게 없어서 참 초라하네요..

저 버튼을 클릭해본다면..?

Spring poi 엑셀 다운로드 - Spring poi egsel daunlodeu

이런 파일이 다운로드 된 것을 확인할 수 있습니다.(아까 설정한 이름이 그래도 나옵니다.)

그리고 이 파일을 열어보면

Spring poi 엑셀 다운로드 - Spring poi egsel daunlodeu

아까 설정했던대로 그대로 엑셀 파일이 출력되는 것을 알 수 있네요.

이렇게 간단한 엑셀 파일 다운로드를 알아봤습니다.

쉽네요 ㅎㅎㅎㅎ(라고 하기엔 저도 되게 어려움을 겪어서 ,,, 알기만 한다면 금방 따라할 수 있습니다.)

그 외에 다른 데이터 형식을 불러와서 엑셀에 추가할 수 도 있습니다.

그런 부분은... 여기까지 했다면 아마 직접할 수 있지 않을까 싶습니다.

시간이 된다면 불러온 데이터를 엑셀에 집어넣어서 다운로드를 받을 수 있는 방법을 적어보겠습니다.

이번 포스트는 제가 굉장히 급해서 적었습니다. ㅎㅎㅎ

처음에 말씀드린 것처럼 다른 블로그 글들은 너무 복잡하더라고요.

스타일 제외하고 정말 필수적인 것만 적었습니다.

그리고 프론트와 백단을 분리해서 해볼려고 했는데,, 급하게 하느라 그런 여유는 없었습니다.

다음에 되면... 그때는 분리해서 진행해보도록 하겠습니다.

이렇게 스프링에서 엑셀파일 다운로드를 마치겠습니다.