1 16 17 package org.springframework.web.servlet.view.document; 18 19 import java.io.OutputStream ; 20 import java.util.Locale ; 21 import java.util.Map ; 22 23 import javax.servlet.http.HttpServletRequest ; 24 import javax.servlet.http.HttpServletResponse ; 25 26 import jxl.Workbook; 27 import jxl.write.WritableWorkbook; 28 29 import org.springframework.core.io.Resource; 30 import org.springframework.core.io.support.LocalizedResourceHelper; 31 import org.springframework.web.servlet.support.RequestContextUtils; 32 import org.springframework.web.servlet.view.AbstractView; 33 34 81 public abstract class AbstractJExcelView extends AbstractView { 82 83 84 private static final String CONTENT_TYPE = "application/vnd.ms-excel"; 85 86 87 private static final String EXTENSION = ".xls"; 88 89 90 91 private String url; 92 93 94 98 public AbstractJExcelView() { 99 setContentType(CONTENT_TYPE); 100 } 101 102 105 public void setUrl(String url) { 106 this.url = url; 107 } 108 109 110 113 protected final void renderMergedOutputModel( 114 Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { 115 116 response.setContentType(getContentType()); 118 OutputStream out = response.getOutputStream(); 119 120 WritableWorkbook workbook; 121 if (this.url != null) { 122 Workbook template = getTemplateSource(this.url, request); 123 workbook = Workbook.createWorkbook(out, template); 124 } 125 else { 126 logger.debug("Creating Excel Workbook from scratch"); 127 workbook = Workbook.createWorkbook(out); 128 } 129 130 buildExcelDocument(model, workbook, request, response); 131 132 135 workbook.write(); 136 out.flush(); 137 workbook.close(); 138 } 139 140 147 protected Workbook getTemplateSource(String url, HttpServletRequest request) throws Exception { 148 LocalizedResourceHelper helper = new LocalizedResourceHelper(getApplicationContext()); 149 Locale userLocale = RequestContextUtils.getLocale(request); 150 Resource inputFile = helper.findLocalizedResource(url, EXTENSION, userLocale); 151 152 if (logger.isDebugEnabled()) { 154 logger.debug("Loading Excel workbook from " + inputFile); 155 } 156 return Workbook.getWorkbook(inputFile.getInputStream()); 157 } 158 159 168 protected abstract void buildExcelDocument( 169 Map model, WritableWorkbook workbook, HttpServletRequest request, HttpServletResponse response) 170 throws Exception ; 171 172 } 173 | Popular Tags |