SpringMVC實現Excel導出

前言:SpringMVC攜帶數據到視圖層經過的是View.class#render()方法,本文的Excel導出將經過擴展View的抽象類AbstractView配合JXLS來實現。java

 

1. 導入jxls相關jar包web

<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模板中。spring

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調用app

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

 

4. Excel模板使用jexl表單式,有興趣的同窗可參考官網:    http://jxls.sourceforge.net/this

相關文章
相關標籤/搜索