Wednesday, April 28, 2010

struts2 annotations下载

使用jexcel生成excel,使用annotations配置下载的参数。

@Results( { @Result(name = BaseDownLoadAction.DOWNLOAD, type = "stream", params = { "contentType", "application/vnd.ms-excel",
"inputName", "inputStream", "contentDisposition", "attachment;filename=\"${downloadFileName}\"", "bufferSize",
"4096" }) })
public class DownLoad2Action extends ActionSupport{
public static final String DOWNLOAD = "download";
private String fileName;// 初始的通过param指定的文件名属性
public String getFile() throws Exception{
setFileName("add的.xls");
return BaseDownLoadAction.DOWNLOAD;
}
public InputStream getInputStream() throws Exception {
WritableWorkbook workbook = Workbook.createWorkbook(new File("d:\\a.xls"));
WritableSheet sheet = workbook.createSheet("测试", 0);

Label label = new Label(0, 0, "hello world 从");
sheet.addCell(label);
workbook.write();
workbook.close();
return new FileInputStream(new File("d:\\a.xls"));
}

/** 提供转换编码后的供下载用的文件名 */
public String getDownloadFileName() {
String downFileName = fileName;
try {
downFileName = new String(downFileName.getBytes(), "ISO8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return downFileName;
}

public void setFileName(String fileName) {
this.fileName = fileName;
}

}


访问的URL:down-load2!getFile.action
params 中使用键值对进行设置:key1,value1,key2,value2.....;对应response相应头

No comments: