1,在业务逻辑层:
public InputStream getInputStream() {
//建立一个exel主界面
HSSFWorkbook book=new HSSFWorkbook();
//创建一个sheet
HSSFSheet sheet=book.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("密码");
List<?> list=this.findByAll();
for(int i=0;i<list.size();i++){
Person person=(Person)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(person.getUsername());
cell=row.createCell((short)2);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(person.getPassword());
}
//这个excel文件会在tomcat的bin目录下生成。
String fileName=RandomCharacter.getRandomString(6);
File file=new File(fileName+".xls");
//File file=new File("text.xls");
try {
OutputStream output=new FileOutputStream(file);
book.write(output);
output.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//返回结果的文件输入文件流,到内存里方便下载
InputStream input=null;
try {
input=new FileInputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return input;
}
2,在Action层:
public InputStream getDownloadFile()
{
return baseService.getInputStream();
}
public String getXls() throws Exception {
this.getDownloadFile();
return SUCCESS;
}
3,在strut.xml中配置:
<result name="success" type="stream">
<param name="contentType">application/vnd.ms-excel</param>
<param name="contentDisposition">attachment;filename="AllUsers.xls"</param>
<param name="inputName">downloadFile</param>
</result>