우디의 개발스터디

[Java] 엑셀 다운로드

by 개발자 우디

Javascript

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();
}

 

 

블로그의 정보

우디의 개발스터디

개발자 우디

활동하기