一、类方法,需要使用poi-2.5.1.jar包:
/*
* 导出Excle文件
*/
public InputStream getInputStream() {
//=======================生成一个Excle模板============================
//生成一个对象,类似Excel
HSSFWorkbook wb=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<Users> list=this.findUserAll();
for (int i = 0; i < list.size(); i++) {
Users 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());
}
//=====运用字节数组输出流和字节数组输入流导出Excle文件,直接在内存中操作,这样不会产生临时文件======
ByteArrayOutputStream baos=new ByteArrayOutputStream();
try {
wb.write(baos);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] content= baos.toByteArray();
InputStream inputStream=new ByteArrayInputStream(content);
return inputStream;
}
二、action
package com.qfx.action;
import java.io.InputStream;
import com.opensymphony.xwork2.ActionSupport;
import com.zpj.service.UserService;
public class WriteEceclAction extends ActionSupport {
private UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}
public InputStream getDownloadFile(){
return this.userService.getInputStream();
}
@Override
public String execute() throws Exception {
return SUCCESS;
}
}
三、struts.xml
<!-- 输出Excel文件 -->
<action name="writeExcel" class="writeExcelAction">
<result name="success" type="stream">
<param name="contentType">application/vnd.ms-excel</param>
<!-- AllUser.xls是页面上要显示的文件名 -->
<param name="contentDisposition">attachment;filename="AllUser.xls"</param>
<param name="inputName">downloadFile</param>
</result>
</action>
四、jsp页面
<s:a href="http://xxx.blog.163.com/blog/writeExcel">在线生成Excel</s:a>