Struts的POI导出Excel文件

原理:先写在内存中,然后读出来打开或下载

在****Action里有如下方法:

 public InputStream getDownloadFile(){
  return this.*Service.getInputStream();
 }
 
 public String getInputStream(){
  return SUCCESS;
 }

 

 

在***Service.java里有getInputStream方法,具体代码如下:

 public InputStream getInputStream() {
  HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
  HSSFSheet hssfSheet = hssfWorkbook.createSheet("sheet1");

  HSSFRow hssfRow = hssfSheet.createRow(0);

  HSSFCell hssfCell = hssfRow.createCell((short) 0);

  hssfCell.setEncoding(HSSFCell.ENCODING_UTF_16);
  hssfCell.setCellValue("列名一");

  hssfCell = hssfRow.createCell((short) 1);
  hssfCell.setEncoding(HSSFCell.ENCODING_UTF_16);
  hssfCell.setCellValue("列名二");

  …………

  //这里获取导出的数据,可根据情况变化
  List<tableName> tableNameList = this.tableNameDao.findAll();
  
  for (int i = 0; i < tableNameList.size(); i++) {
   TableName tableName = tableNameList.get(i);
   hssfRow = hssfSheet.createRow(i+1);

   hssfCell = hssfRow.createCell((short) 0);
   hssfCell.setEncoding(HSSFCell.ENCODING_UTF_16);
   hssfCell.setCellValue(tableName.get***());// 列一填充数据

   hssfCell = hssfRow.createCell((short) 1);
   hssfCell.setEncoding(HSSFCell.ENCODING_UTF_16);
   hssfCell.setCellValue(tableName.get***());

……………………

  }
  //创建文件用10个长度的随机名
  File tableNameFile = new File(new StringBuffer(RandomStringUtils.randomAlphanumeric(10)).append(".xls").toString());
  // 创建输出流
  try {
   OutputStream outputStream = new FileOutputStream(tableNameFile);
   hssfWorkbook.write(outputStream);
   outputStream.close();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  // 创建输入流
  InputStream inputStream = null;;
  try {
   inputStream = new FileInputStream(tableNameFile);
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }
  return inputStream;
 }

 

struts.xml里面配置

<action name="l" method="getInputStream" class="***Action">
   <result name="success" type="stream">
    <param name="contentType">application/vnd.ms-excel</param>
    <param name="contentDisposition">attachment;filename="必须英文名字.xls"</param>
    <param name="inputName">downloadFile</param>
    <param name="bufferSize">1024</param>
   </result>
  </action>

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值