자바 엑셀 파일로 추출하기

Woody·2022년 1월 2일
post-thumbnail

간단하게 Javascript 에서 요청을 보내 Controller 에서 바로 약식으로 엑셀 파일을 만들어주는 한 사이클이다.

JS 요청코드

function excelDownload(){
	$("#searchForm").attr("action", "/adm/board/excel/download");
	$("#searchForm").submit();
}

Controller

@ResponseBody
@RequestMapping(method = RequestMethod.POST, value = "/excel/download")
public void excelDownload(HttpServletResponse response, BoardParam param) throws IOException {
	param.setPageSize(null);

	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("작성자");
	cell = row.createCell(3);
	cell.setCellValue("작성일");
	// Body
	List<Board> list = service.listBoard(param);
	for(Board board : list){
		row = sheet.createRow(rowNum++);
		cell = row.createCell(0);
		cell.setCellValue(board.getRowNum());
		cell = row.createCell(1);
		cell.setCellValue(board.getTitle());
		cell = row.createCell(2);
		cell.setCellValue(board.getWriteName());
		cell = row.createCell(3);
		cell.setCellValue(board.getWritedt());
	}

	sheet.autoSizeColumn(1);
	sheet.autoSizeColumn(3);
    
	// 컨텐츠 타입과 파일명 지정
	response.setContentType("ms-vnd/excel");
	response.setHeader("Content-Disposition", "attachment;filename=board.xlsx");
    
	wb.write(response.getOutputStream());
	wb.close();
}
profile
If the wind will not serve, take to the oars

0개의 댓글