반응형

자바를 이용해서 엑셀 다운로드 기능을 구현하는 방법입니다.

샘플 엑셀파일 없이 자체적으로 생성하는 방법입니다.

.xlsx 확장자를 생성합니다.

 

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RequestMapping("/excelDown.do")
public void excelDown(HttpServletResponse response) throws IOException{

    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet();
    XSSFRow row = null;
    XSSFCell cell = null;

    int rowIndex = 0;
    int cellIndex = 0;
    
    row = sheet.createRow(rowIndex++);
    
    String[] colName = {"컬럼1", "컬럼2", "컬럼3"};
    int[] colWidth = {3000, 5000, 10000};

    // 헤더 추가
    for (int i = 0; i < colName.length; i++){
        cell = row.createCell(i);
        cell.setCellValue(colName[i]);
        sheet.setColumnWidth(i, colWidth[i]); // 컬럼 너비 설정
    }

    // 바디 추가
    String[] row1 = {"값1", "값2", "값3"};
    String[] row2 = {"값4", "값5", "값6"};
    String[] row3 = {"값7", "값8", "값9"};

    List<String[]> testList = new ArrayList<>();
    testList.add(row1);
    testList.add(row2);
    testList.add(row3);

    for (String[] test : testList){
        cellIndex = 0;
        row = sheet.createRow(rowIndex++);

        cell = row.createCell(cellIndex++);
        cell.setCellValue(test[0]);

        cell = row.createCell(cellIndex++);
        cell.setCellValue(test[1]);

        cell = row.createCell(cellIndex++);
        cell.setCellValue(test[2]);
    }

    String fileName = URLEncoder.encode("엑셀 다운 테스트", "UTF-8");
    fileName = fileName.replaceAll("\\+", "%20"); // 파일명에 공백 + 로 나오는거 공백으로 변환

    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

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

 

해당 소스로 돌려보시면 바로 기능 구현 확인 가능합니다.

샘플 소스라 하드코딩으로 작성하였는데 헤더와 바디부분을 수정하면 원하는 형식으로 활용할 수 있습니다.

반응형

+ Recent posts