主要关注@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配置文件应该也不会有问题。
转载请注明出处...