<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
controller层
//
String path= servicen层调用downloadAgentlistData();
//path="D:/tomcat/8080/webapps/ROOT/WEB-INF/classes/temp/xxxxxx.xls";
String fileName = "xx"+ DateUtil.date2StrShort(new Date()).replace("-", "")+".xls";
return getResponseEntity(filepath, fileName);
/**
* 生成响应内容
* @param filepath
* @param fileName
* @return
*/
private ResponseEntity<byte[]> getResponseEntity(String filepath,String fileName){
HttpHeaders headers = new HttpHeaders();
byte[] bytes = null;
if(!"".equals(filepath)){
bytes = FileUtils.File2byte(filepath);
}
try {
headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("utf-8"),"ISO8859-1"));
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
} catch (UnsupportedEncodingException e) {
e.getMessage();
}
return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.CREATED);
}
service方法
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
private final Log logger = LogFactory.getLog(getClass());
public String downloadAgentlistData() throws Exception {
//导出推广计划相关数据
String tempPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String targetFilePath = tempPath+"/temp/AdExtendDownload.xls";
//打开模板
Workbook wb = null;
WritableWorkbook wwb=null;
try {
File targetFiles = new File(targetFilePath);
File file=new File(tempPath + "//temp//AdExtendDownload.xls");
wb = Workbook.getWorkbook(file);
wwb = Workbook.createWorkbook(targetFiles, wb);
WritableSheet wws0 = wwb.getSheet(0);
wws0.addCell(new Label(1,0,""));
wws0.addCell(new Label(1,1,""));
wws0.addCell(new Label(1,3,""));
wws0.addCell(new Label(2,3,""));
wws0.addCell(new Label(3,3,""));
wws0.addCell(new Label(4,3,""));
wws0.addCell(new Label(5,3,""));
wws0.addCell(new Label(6,3,""));
if(null!=orderList&&orderList.size()>0)
{
for(int i=0;i<orderList.size();i++){
AdOrder order = orderList.get(i);
wws0.addCell(new Label(0,5+i,""));
wws0.addCell(new Label(1,5+i,""));
}
}
wwb.write();
} catch (Exception e) {
logger.error(e.getMessage());
throw new Exception("下载平台汇总数据出错!");
} finally{
if(wb!=null){
wb.close();
}
if(wwb!=null){
try {
wwb.close();
} catch (Exception e) {
logger.error(e.getMessage());
throw new Exception("下载平台汇总数据出错!");
}
}
}
return targetFilePath;
}
导入jxl.jar 包