poi 生成excel

来源:互联网 发布:海川新盟软件下载 编辑:程序博客网 时间:2024/06/05 04:58

interface--UserService

 public InputStream getInputStream();


UserServiceImpl


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("密码");


List<User> list=this.ListAll();

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.getUsername());

cell=row.createCell((short)2);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(user.getPassword());

}


File file=new File("user.xls");
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();
}


return is;

}


struts.xml

   <action name="gerenateExcel" class="generateExcelAction">
     <result name="success" type="stream">
         <param name="contentType">application/vnd.ms-excel</param>
         <param name="contentDisposition">file="AllUsers.xls"</param>
          <param name="inputName">downloadFile</param>
     
     </result>package com.test.action;

          </action>


----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();
}

public String execute()
{

return "success";
}
}