블랙디의 개발새발

[Spring boot] Spring REST API Excel down / REST Controller에서 엑셀 다운로드 하기/ REST API Download Excel file 본문

IT Program/Java Tip

[Spring boot] Spring REST API Excel down / REST Controller에서 엑셀 다운로드 하기/ REST API Download Excel file

BlackD 2020. 10. 11. 13:03

스프링부트 엑셀다운, 스프링부트 rest api 엑셀다운

엑셀 다운로드는 poi 라이브러리를 사용한 방식이 있습니다. 대부분의 방식은 front단에서 객체를 받아 poi를 이용해서 엑셀로 다운로드하게 됩니다.

오늘은 REST API Controller에서 엑셀을 다운하는 법을 알아보겠습니다. 도움이 되셨다면 좋아요와 댓글~!

 

 

안녕하세요 프로그래머 블랙디입니다.

 

1. REST API Controller 

  Get 매핑으로 api형식을 정의하고 response 타입과 헤더를 set합니다. 

 그리고, Stream 형식으로 output하게 됩니다.

 

 

       @GetMapping(value="/RestExcel")

       public void RestExcel(HttpServletResponse response) throws IOException{

              //만약 대용량의 데이터를 추출할 때에는 타입을 application/json으로 해보시길 바랍니다.

              response.setContentType("application/octet-stream");

              //첨부파일의 다운로드 이름을 설정합니다.

              response.setHeader("Content-Disposition", "attachment; filename=excelFileName.xlsx");

              

             //객체 생성

             List<Customer> customers = new ArrayList<Customer>();

            customers.add(new Customer("Customer1", "customers", "01012345678", "Customer1@blackd.com"));

            customers.add(new Customer("Customer2", "customers", "01012345678", "Customer1@blackd.com"));

            customers.add(new Customer("Customer3", "customers", "01012345678", "Customer1@blackd.com"));

            customers.add(new Customer("Customer4", "customers", "01012345678", "Customer1@blackd.com"));

            customers.add(new Customer("Customer5", "customers", "01012345678", "Customer1@blackd.com"));

 

              //poi를 활용해서 엑셀 데이터를 만듭니다. 2번 참고

              ByteArrayInputStream stream = ExcelUtil.createListToExcel(customers);

              IOUtils.copy(stream, response.getOutputStream());

       }

 

2. Rest 형식의 Excel 생성

public static ByteArrayInputStream createListToExcel(List<Customer> customers) {

             try(Workbook workbook = new XSSFWorkbook()){

                    Sheet sheet = workbook.createSheet("Customers");

                    

                    Row row = sheet.createRow(0);

               CellStyle headerCellStyle = workbook.createCellStyle();

               headerCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());

               headerCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

               // Creating header

               Cell cell = row.createCell(0);

               cell.setCellValue("First Name");

               cell.setCellStyle(headerCellStyle);

              

               cell = row.createCell(1);

               cell.setCellValue("Last Name");

               cell.setCellStyle(headerCellStyle);

       

               cell = row.createCell(2);

               cell.setCellValue("Mobile");

               cell.setCellStyle(headerCellStyle);

       

               cell = row.createCell(3);

               cell.setCellValue("Email");

               cell.setCellStyle(headerCellStyle);

              

               // Creating data rows for each customer

               for(int i = 0; i < customers.size(); i++) {

                    Row dataRow = sheet.createRow(i + 1);

                      dataRow.createCell(0).setCellValue(customers.get(i).getFirstName());

                      dataRow.createCell(1).setCellValue(customers.get(i).getLastName());

                      dataRow.createCell(2).setCellValue(customers.get(i).getMobileNumber());

                      dataRow.createCell(3).setCellValue(customers.get(i).getEmail());

               }

       

               // Making size of column auto resize to fit with data

               sheet.autoSizeColumn(0);

               sheet.autoSizeColumn(1);

               sheet.autoSizeColumn(2);

               sheet.autoSizeColumn(3);

              

               ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

               workbook.write(outputStream);

               return new ByteArrayInputStream(outputStream.toByteArray());

             } catch (IOException ex) {

                    ex.printStackTrace();

                    return null;

             }

       }

 

 

이상으로 Rest api로 Excel 다운로드하기에 대해서 알아보았습니다. 

 

더 궁금한 사항이 있으신 분은 댓글로 남겨주세요. 이상 BlackD 였습니다.

'IT Program > Java Tip' 카테고리의 다른 글

[Java] jframe 예제 그리고 jframe 이란  (0) 2019.10.30
Comments