最近做了一个需求,点击页面生成并下载Excel文件,现记录下来,便于以后回顾!

POI的Maven配置如下:

<dependency>  
     <groupId>org.apache.poi</groupId>  
     <artifactId>poi</artifactId>  
     <version>3.9</version>  
</dependency>

 

struts.xml的配置如下:

<action name="downloadWorkload" class="DownloadWorkloadAction" method="exportExcel">
  <result name="success" type="stream">
    <param name="contentType">application/vnd.ms-excel</param>
    <param name="inputName">excelStream</param>
    <param name="contentDisposition">attachment;filename=${excelFileName}</param>  
    <param name="bufferSize">4096</param>  
  </result>
</action>

其中,stream类型的结果共可以指定7个参数:

  • contentType:下载文件的类型。
  • contentLength:下载文件的长度,用于浏览器的进度条显示。
  • contentDisposition:指定文件下载的默认名字,如果不指定则使用Action名.action。
  • inputName:Action中用于返回InputStream的get方法的名字,默认为inputStream,因此,我们的Action中定义了getInputStream的方法。
  • bufferSize:缓冲区大小,默认为(4096)即4k。
  • allowCaching:是否允许浏览器进行缓存。
  • contentCharSet:HTTP响应头信息中的编码方式。

配好struts2的配置之后,就可以写整个Action的业务逻辑了,可以分为以下两步:

1.将目标数据写入POI的 HSSFWorkbook 对象中:

HSSFWorkbook wb = new HSSFWorkbook();
  HSSFSheet sheet = wb.createSheet(“test.xls”);
  HSSFRow titleRow = sheet.createRow(0);
  for (int i = 0; i < titleArray.length; i++) {
    HSSFCell cell = titleRow.createCell(i);
    cell.setCellValue(titleArray[i]);
  }

2.将生成 HSSFWorkbook  对象写入InputStream流中,可以使用ByteArrayInputStream或者FileInputStream,会有不同效果:

  1)使用ByteArrayInputStream,将数据写入字节流数组,直接输出,在服务器不会产生excel文件;

  ByteArrayOutputStream os = new ByteArrayOutputStream(); 
  wb.write(os);
  os.flush();
  byte[] fileContent = os.toByteArray(); 
  excelStream = new ByteArrayInputStream(fileContent);
  os.close();

  2)使用FileInputStream,将数据写入文件流,在服务器会产生excel文件;

  File file = new File("/data/" + excelFileName);
  FileOutputStream writer
= new FileOutputStream(file);
  wb.write(writer);
  excelStream
= new FileInputStream(file);   writer.close();

  部署好工程后,就可以通过URL访问服务器,下载Excel文件了!

 

  参考资料:http://blog.csdn.net/zht666/article/details/11091505

posted on 2014-11-26 20:29  离不开水的鱼  阅读(1987)  评论(0)    收藏  举报