Struts2通过流格式生成Excel下载文件

在工作中需要在JSP页面中,将POI生成的Excel文件直接下载,开发平台是基于Struts2+Spring2的,在网上查了一下,例子不少,也都给我提供了一定的帮助,但很少有拿来不需要进行调试就直接能用的代码例子。所以我把自己最后的实现代码贴出来,希望能对后来者有一定的帮助,或许实现方法不是最好的,但应该是不需要进行过多调试就可以直接用的。
主要关注@Result的params参数设置部分的代码


public class EfficDataAction extends ActionSupport {

//...省略部分代码
private InputStream inputStream;
private String contentDisposition;
private String documentFormat = "xls";
private String contentType;

public String getContentType() {
return documentFormat == "xlsx" ? "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
: "application/vnd.ms-excel;charset=ISO8859-1";
}

@Resource
private EfficDataService efficdataservice;

public String getContentDisposition() {
return contentDisposition;
}

public InputStream getInputStream() {
return inputStream;
}

public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}

public void setContentDisposition(String contentDisposition) {
this.contentDisposition = contentDisposition;
}

public String getDocumentFormat() {
return documentFormat;
}

public void setDocumentFormat(String documentFormat) {
this.documentFormat = documentFormat;
}

public EfficDataService getEfficdataservice() {
return efficdataservice;
}

@Resource
public void setEfficdataservice(EfficDataService efficdataservice) {
this.efficdataservice = efficdataservice;
}

//...省略部分代码

//这里的params参数配置是关键
@Action(value = "/createefficfile", results = { @Result(name = "success", type = "stream") }, params = {
"contentType", "${contentType}", "inputName", "${inputStream}",
"contentDisposition", "${contentDisposition}", "bufferSize", "2048" })
public String createefficfile() throws Exception {

ByteArrayOutputStream baos = new ByteArrayOutputStream();

//...下面的3行代码是我生成Excel文件用的,请更具实际需要裁减
HSSFWorkbook book = new HSSFWorkbook();
book = efficdataservice.createEfficCollectFile(this);
book.write(baos);

//...下面的代码是设置Excel文件下载的一些必须内容
//...文件名需要进行转码,不然中文的话可能会有问题
this.setInputStream(new ByteArrayInputStream(baos.toByteArray()));
this.setContentDisposition("filename=\\"
+ java.net.URLEncoder.encode(getUploadFileFileName(), "UTF-8")
+ getDocumentFormat());

return "success";
}

}



我是用注解来配置Struts2的Action的,用xml配置文件应该也不会有问题。

转载请注明出处...
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值