`
yoshikilu
  • 浏览: 9466 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

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配置文件应该也不会有问题。

转载请注明出处...
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics