1. Dependency Library 추가


Java Poi 라이브러리를 사용 Maven pom.xml 에 추가 하자.


<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.0.2-FINAL</version>
</dependency>


2. AbstractExcelView 구현 하기


Spring 에서 제공 하는 AbstractView 기능을 확장하여 사용 한다.

TestExcelView.java
@Component("TestExcelView")
public class TestExcelView extends AbstractExcelView {

    @Override
    protected void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        HSSFSheet sheet = workbook.createSheet();
        HSSFRow header = sheet.createRow(0);
        header.createCell((short) 0).setCellValue("Test1");
        header.createCell((short) 1).setCellValue("Test2");
        header.createCell((short) 2).setCellValue("Test3");
        header.createCell((short) 3).setCellValue("Test4");
        header.createCell((short) 4).setCellValue("Test5");

        HSSFRow row = sheet.createRow(1);
        row.createCell((short) 0).setCellValue("Test1");
        row.createCell((short) 1).setCellValue("Test2");
        row.createCell((short) 2).setCellValue("Test3");
        row.createCell((short) 3).setCellValue("Test4");
        row.createCell((short) 4).setCellValue("Test5");
    }

}


3. Controller 구현 하기


ModelAndView Return 시 앞서 구현한 TestExcelView 로 변경 하자.

TestController.java
@RequestMapping(value="/testExcel.xls", method=RequestMethod.GET)
public ModelAndView testExcel(HttpServletRequest request) {
    ModelAndView mav = new ModelAndView();

    mav.setViewName("TestExcelView");

    return mav;
}


4. 요청 하기


http://localhost:8080/testExcel.xls

참고 서적
  • Spring Recipes - A Problem-Solution Approach, 2nd Edition (Apress, 2010) (364~365)


+ Recent posts