jhhan의 블로그

Spring - Excel Download(3) 본문

Spring & Vue.js

Spring - Excel Download(3)

jhhan000 2021. 1. 30. 22:44

스프링으로 엑셀 다운로드 3편입니다.

이렇게까지 오래 다룰 줄은 몰랐네요.

그래도 오류가 있다면 고쳐야겠죠

 

지난번까지 진행을 한다면 오류가 생기는 것을 볼 수도 있습니다(?)

이런 에러가 뜨는 것을 볼 수 있습니다.
(사실 에러는 아니네요. warning이군요)

그리고 지금까지 createTempFile을 사용했기 때문에... 이런 로직을 계속 진행하면

val file = File.createTempFile("testExcel_", ".xlsx")

로컬 컴퓨터 혹은 서버로 사용되는 컴퓨터에 계속해서 temp 파일이 쌓이게 됩니다..

그걸 계속해서 지워주지 않는다면, 컴퓨터의 용량을 언젠가는 굉장히 많이 차지하게 될 것입니다.

그걸 방지해줘야 합니다.

 

방법은

  1. createTempFile로 생성된 임시파일을 지워준다.
  2. 아예 Temp File이 생성되지 않게 로직을 변경한다.

2개로 볼 수 있겠네요.

1번은 시도했는데, 저는 안되더라구요..

그래서 1번은 포기하고, 2번으로 진행했습니다.

    @PostMapping("/excel3")
    fun getExcelFile3(@RequestBody iadList: List<IntAndDouble>, response: HttpServletResponse) {
        println("Excel Start-3!")
        for (iad in iadList) {
            println(iad)
        }

        val wb = XSSFWorkbook()
        val sheet = wb.createSheet("sheet1")
        var row: Row?
        var rowNum = 0

        row = sheet.createRow(rowNum++)
        row.createCell(0).setCellValue("Mode")
        row.createCell(1).setCellValue("Affinity")
        row.createCell(2).setCellValue("lb")
        row.createCell(3).setCellValue("ub")
        row.createCell(4).setCellValue("url1")
        row.createCell(5).setCellValue("url2")

        for(iad in iadList) {
            row = sheet.createRow(rowNum++)
            row.createCell(0).setCellValue(iad.mode.toDouble())
            row.createCell(1).setCellValue(iad.affinity)
            row.createCell(2).setCellValue(iad.lb)
            row.createCell(3).setCellValue(iad.ub)
            row.createCell(4).setCellValue(iad.pUrl)
            row.createCell(5).setCellValue(iad.qUrl)
        }

        try {
            response.contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            response.setHeader("Content-Disposition", "attachment; filename=\"example.xlsx\"")
            wb.write(response.outputStream)
        } catch (e: Exception) {
            println(e)
            throw e
        } finally {
            wb.close()
        }
    }
  • 그리고 리턴값도 없앴습니다.(kotlin에서는 Unit 리턴이라고 합니다. Unit은 void라고 생각하면 됩니다.)
  • 다른 블로그들을 찾아봐도 대부분 리턴값이 없습니다.
  • 역시 ... 많은 사람들이 그렇게 적는데에는 이유가 있습니다.
  • try - catch - finally 구문을 이용해서 진행했습니다.
  • try : 엑셀 파일을 만들 수 있는 구문입니다.
          따지면 outputStream을 바로 리턴하는 것으로 봐도 됩니다.
  • catch : 에러가 생길 때 여기서 진행됩니다.
  • finally : 모든 로직이 끝나면 close()를 사용해서 사용 해제를 합니다.

 

그리고 ... 이에 맞게 front뷰도 따로 작성해주셔야 겠지요..

이전에 작성한 것과 굉장히, 매우 유사해서 따로 적기가 싫지만,,,

그래도 백과 프론트 모두 다뤄야 하니까요 

겹치는 내용이 많지만 그래도 적어야 합니다 ㅎㅎ

    <div>
      <button @click="makeExcelFile3">Excel3</button>
    </div>
    makeExcelFile3 () {
      console.log("Excel-3!")
      axios.post(process.env.VUE_APP_API_ENDPOINT + "/excel3", this.data1, {
        responseType: 'arraybuffer'
      })
          .then(result => {
            console.log(result)
            const url = window.URL.createObjectURL(new Blob([result.data], { type: result.headers["content-type"] }))
            const link = document.createElement("a")
            link.href = url
            link.download = "example.xlsx"
            link.click()
            window.URL.revokeObjectURL(url)
          }).catch(er => {
            console.log(er)
          })
    }

이렇게 추가를 합니다.

그리고 백엔드와 프론트를 모두 실행합니다.

이렇게 Excel3 버튼이 추가가 되었습니다...  ㅋㅋ

그럼 Excel3 버튼을 눌러본다면...?

  • 이전에 그랬던 것처럼 엑셀 파일이 잘 다운로드 됩니다.
  • temp 파일은 생성되지 않습니다.
  • warning이 따로 뜨지 않습니다.

 

이렇게 엑셀 다운로드를 3편까지 진행해서 알아봤네요...

이번에는 예정에 없던 것을 또 작성하는 것이고, 

코드도 큰 변화가 없어서... 내용이 짧습니다.

오히려 말을 많이 해서 글이 길어졌습니다.

 

그리고..

이렇게까지 했으니.. 아마 엑셀 다운로드를 잊어먹기는 쉽지 않을 것 같습니다.

 

 

이렇게 스프링 - 엑셀 다운로드 3편을 마칩니다.

'Spring & Vue.js' 카테고리의 다른 글

Spring - Excel Download(2)  (0) 2021.01.19
Spring - Excel Download  (0) 2021.01.12
Spring + Vue.js(3)  (1) 2020.08.02
Spring & Vue.js  (0) 2020.06.11
Spring & Vue.js 연동  (5) 2020.05.13