struts.xml的配置
<action name=”generateExcel” class=”generateExcelAction”>
<result name=”success” type=”stream”>
<param name=”contentType”>application/vnd.ms-excel</param>
<param name=”contentDisposition”>attachment;fileName=”AllUser.xls”</param> <!– attachment弹出窗口,inline在浏览器上打开–>
<param name=”inputName”>downloadFile</param>
</result>
</action>
applicationContext.xml配置
<bean id=”generateExcelAction” class=”com.xk.action.user.GenerateExcelAction” scope=”singleton”>
<property name=”service” ref=”userService”></property>
</bean>
GenerateExcelAction.java
package com.xk.action.user;
import java.io.InputStream;
import com.opensymphony.xwork2.ActionSupport;
import com.xk.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() //这个方法要与struts.xml中inputName的值匹配,此处即downloadFile–对应–getDownloadFile()
{
return this.service.getInputStream(); //调用service的getInputStream方法
}
@Override
public String execute() throws Exception {
return SUCCESS;
}
}
UserServiceImpl.java中的getInputStream方法
public InputStream getInputStream() {
HSSFWorkbook wb = new HSSFWorkbook();
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 = userDao.findAllUser();
User user = null;
for(int i=0;i<list.size();i++)
{
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());
}
String filename = RandomStringUtils.randomAlphanumeric(10);//随即生成长度为10包含字母和数字的字符串
filename = filename+”.xls”;
File file = new File(filename);
try {
OutputStream os = new FileOutputStream(file);
wb.write(os);
} catch (Exception e) {
e.printStackTrace();
}
InputStream is = null;
try {
is = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return is;
}