struts2实现对查询结果的下载

来源:互联网 发布:2017年旅游数据 编辑:程序博客网 时间:2024/05/21 15:06

参考自: http://blog.csdn.net/u010244138/article/details/17124719

jsp: <a href="export.action">导出查询结果</a>

Struts.xml <action name="export" class="action.StudentAction" method="export">
<result name="data" type="streamx">
<param name="contentType">application/vnd.ms-excel</param>
        <param name="inputName">inputStream</param>
</result>

</action>

action: 

List<Student> ExcelList=null;
@SuppressWarnings("unchecked")
public String export(){
Map<String,Object> session=ActionContext.getContext().getSession();
ExcelList=(List<Student>)session.get("excelList");
HttpServletResponse response=ServletActionContext.getResponse();

//创建工具表
WritableWorkbook table=null;
OutputStream os=null;
try{
response.setContentType("application/x-msdownload");
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddhhmmss");
//文件名,以当前秒为文件名
String fileName=sdf.format(new Date());
//设置生成的文件名字
response.setHeader("Content-Disposition", "attachment;filename="+fileName+".xls");
os=response.getOutputStream();

//初始化工作表
table=Workbook.createWorkbook(os);
}catch(IOException el){
el.printStackTrace();
}

try{
WritableSheet sheet=table.createSheet("学生信息",0);
//字段名 (列 行)
sheet.addCell(new jxl.write.Label(0,0,"学号"));
sheet.addCell(new jxl.write.Label(1,0,"姓名"));
sheet.addCell(new jxl.write.Label(2,0,"年龄"));
//添加数据
for(int i=1;i<ExcelList.size();i++){
sheet.addCell(new jxl.write.Label(0,i,ExcelList.get(i-1).getId()));
sheet.addCell(new jxl.write.Label(1,i,ExcelList.get(i-1).getName()));
sheet.addCell(new jxl.write.Label(2,i,String.valueOf(ExcelList.get(i-1).getAge())));
}
table.write();
table.close();
os.close();
//os.pageContext.pushBody();
}catch(Exception e){
e.printStackTrace();
}
return "data";
}


0 0