笑我痴狂 发表于 2013-1-15 02:24:04

struts2 支持的下载以及如何动态生成excel表格文件

struts2支持的下载 , 以及下载方法的实现方式

先说struts的实现

配置struts.xml
<action name="generateExcel" class="generateExcelAction"><result name="success" type="stream"><param name="contentType">application/vnd.ms-excel</param><param name="contentDisposition">attachment;afilename="AllUsers.xls"</param><param name="inputName">downloadFile</param></result></action>


import java.io.InputStream;import com.opensymphony.xwork2.ActionSupport;import com.test.service.UserService;public class GenerateExcelAction extends ActionSupport{private UserService service;//服务层的接口public UserService getService(){return service;}public void setService(UserService service){this.service = service;}public InputStream getDownloadFile(){return this.service.getInputStream();}@Overridepublic String execute() throws Exception{return SUCCESS;}}


jsp页面
<s:a href="generateExcel.action">生成excel</s:a>


jsp点击提交到generateExcel,
generateExcel返回“success”视图 ,由struts.xml的配置可以看出success视图有三个参数
<param name="contentType">application/vnd.ms-excel</param>//文件的类型<param name="contentDisposition">attachment;afilename="AllUsers.xls"</param>//attachment的解释 ,此参数默认值为inline ,如果是inline 会在浏览器中打开该//文件,如ppt,txt会直接在浏览器上显示,但有些文件是不能再浏览器中打开的 ,如//果选择attachment ,则不管是什么格式都会弹出一个下载框供用户选择 <param name="inputName">downloadFile</param>//说明提交到action的downloadFile执行


public InputStream getDownloadFile(){return this.service.getInputStream();}

package com.test.service.impl;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.util.List;import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.usermodel.HSSFRow;import org.apache.poi.hssf.usermodel.HSSFSheet;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import com.test.bean.User;import com.test.dao.UserDAO;import com.test.service.UserService;public class UserServiceImpl implements UserService{private UserDAO userDao;public UserDAO getUserDao(){return userDao;}public void setUserDao(UserDAO userDao){this.userDao = userDao;}public void delete(User user){this.userDao.removeUser(user);}public List<User> findAll(){return this.userDao.findAllUsers();}public User findById(Integer id){return this.userDao.findUserById(id);}public void save(User user){this.userDao.saveUser(user);}public void update(User user){this.userDao.updateUser(user);}public InputStream getInputStream(){//spring对execle格式下载提供了支持 对应spring中的poi.jar包HSSFWorkbook wb = new HSSFWorkbook();//new 一个HSSFWorkbook实例 //创建一个sheet脚本HSSFSheet sheet = wb.createSheet("sheet1");       //创建一行 ,第一行是标题如 姓名 性别 年龄HSSFRow row = sheet.createRow(0);      //往第一行上插入单元格 HSSFCell cell = row.createCell((short) 0);cell.setEncoding(HSSFCell.ENCODING_UTF_16);cell.setCellValue("序号");cell = row.createCell((short) 1);cell.setEncoding(HSSFCell.ENCODING_UTF_16);cell.setCellValue("姓");cell = row.createCell((short) 2);cell.setEncoding(HSSFCell.ENCODING_UTF_16);cell.setCellValue("名");cell = row.createCell((short) 3);cell.setEncoding(HSSFCell.ENCODING_UTF_16);cell.setCellValue("年龄");      //获取要生成表的数据List<User> list = this.findAll();       //以行的形式出入表格中for (int i = 0; i < list.size(); ++i){User user = list.get(i);row = sheet.createRow(i + 1);cell = row.createCell((short) 0);cell.setEncoding(HSSFCell.ENCODING_UTF_16); //设置字符的类型cell.setCellValue(i + 1);cell = row.createCell((short) 1);cell.setEncoding(HSSFCell.ENCODING_UTF_16);cell.setCellValue(user.getFirstname());cell = row.createCell((short) 2);cell.setEncoding(HSSFCell.ENCODING_UTF_16);cell.setCellValue(user.getLastname());cell = row.createCell((short) 3);cell.setEncoding(HSSFCell.ENCODING_UTF_16);cell.setCellValue(user.getAge());}//问题:上序代码在内存中创建了一个execle表格 ,如何下载到本地//解决方案一:在本地new一个临时file ,把内存中的数据写道本地file中 ,再用inputstream供用户下载//解决方案二:在内存中直接下载到本地(性能好)//以下对这两种方式都做了实现ByteArrayOutputStream os = new ByteArrayOutputStream();try{wb.write(os);}catch (IOException e){e.printStackTrace();}byte[] content = os.toByteArray();InputStream is = new ByteArrayInputStream(content);return is;//       以下是以临时文件的形式实现的//byte[] content = wb.getBytes();//InputStream is = new ByteArrayInputStream(content);////return is; //以下两种方式取得文件名(任选其一)其中CharacterUtils是自定义的一个工具类//// String fileName = CharacterUtils.getRandomString(10);//RandomStringUtils是源包下的一个工具类//String fileName = RandomStringUtils.randomAlphanumeric(10);////fileName = new StringBuffer(fileName).append(".xls").toString();////final File file = new File(fileName);////try//{//OutputStream os = new FileOutputStream(file);//wb.write(os);//os.close();//}//catch (Exception e)//{//e.printStackTrace();//}////InputStream is = null;//try//{//is = new FileInputStream(file);//}//catch (FileNotFoundException e)//{//e.printStackTrace();//}////new Thread(new Runnable()//{//public void run()//{//try//{//Thread.sleep(15000);//}//catch (InterruptedException e)//{//e.printStackTrace();//}////file.delete();//删除临时文件 //}//}).start();////return is;}}

事例如下

http://dl.iteye.com/upload/attachment/278506/86477be8-be18-3ef5-9d8c-36ebd7671a6f.jpg

点击生成excle表
下载后以.xsl格式打开

http://dl.iteye.com/upload/attachment/278509/b14657d8-cea9-3130-b2db-5ea9b0776b08.jpg


如果需要完整的代码请下载后运行
相关的jar包请点击http://wuzhaohuixy-qq-com.iteye.com/blog/711892下载三个zip包 ,解压后加入项目的lib下
页: [1]
查看完整版本: struts2 支持的下载以及如何动态生成excel表格文件