前言:SpringMVC携带数据到视图层通过的是View.class#render()方法,本文的Excel导出将通过扩展View的抽象类AbstractView配合JXLS来实现。

 

1. 导入jxls相关jar包

<dependency>
  <groupId>net.sf.jxls</groupId>
   <artifactId>jxls-core</artifactId>
   <version>1.0.6</version>
</dependency>
<dependency>
  <groupId>net.sf.jxls</groupId>
  <artifactId>jxls-reader</artifactId>
  <version>1.0.6</version>
</dependency>

 

2. 自定义ExcelTemplateView继承于AbstractView。重点是renderMergedOutputModel(),作用是将model中的数据合并到Excel模板中。

public class ExcelTemplateView extends AbstractView {
  
  /* (non-Javadoc)
   * @see org.springframework.web.servlet.view.AbstractView#renderMergedOutputModel(java.util.Map, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
   */
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, 
                          HttpServletResponse response) throws Exception {

     // 1. create workbook by template
        File template = ResourceUtils.getFile("classpath:/template" + templateExcelFile);
        Workbook workbook = WorkbookFactory.create(template);
        
        // 2. transfer model data to workbook
        XLSTransformer transformer = new XLSTransformer();
        transformer.transformWorkbook(workbook, model);
        
        // 3. set disposition
        response.setHeader("Content-Disposition", "attachment; filename=download.xlsx");
        
        // 4. no cache here
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");  
        response.setDateHeader("Expire", 0); 
        response.setContentType("application/vnd.ms-excel");
        
        ServletOutputStream outputStream = response.getOutputStream();

        workbook.write(outputStream);
        outputStream.flush();

        logger.info("End exporting excel file: " + this.templateExcelFile);
        
    }
}

 

3. Controller调用

ModelAndView modelAndView = new ModelAndView(new ExcelTemplateView("template.xlsx"));
modelAndView.addObject("dataList", dataList);
return modelAndView;