2016-02-19 56 views
0

我正在用Apache POI创建一个Excel文件,并将它保存到FileOutputStream中。FileOutputStream到StreamedContent

在XHTML中,我想用<p:fileDownload>下载此文件,但它需要StreamedContent才能工作。

我想知道如何解析或投射我的FileOutputStreamStreamedContent下载PrimeFaces。

+0

请访问http://计算器。 com/a/15970438/3365426 –

+0

DefaultStreamedContent需要一个FileInputStream,但我已经有一个FileOutputStream – Oscarmageddon

+0

然后寻找方法将输出流转换为输入流 – Kukeltje

回答

-2

我必须将我的文件保存到磁盘中,稍后再用File类型读取它以将其保存到StreamedContent中。

代码:

HSSFWorkbook libro = new HSSFWorkbook(); 
FileOutputStream elFichero = new FileOutputStream("c:/Temp/MyExcel.xls"); 
     libro.write(elFichero); 
     elFichero.close(); 
     libro.close(); 
     File fil = new File("c:/Temp/MyExcel.xls"); 
     StreamedContent excel = new DefaultStreamedContent(new FileInputStream(fil), new MimetypesFileTypeMap().getContentType(fil), "MyExcel.xls")); 

后,我能在<p:commandButton>得到我的Excel文件。

反正我一直在寻找一种方式来尽量不要下载之前将其保存到磁盘...

1

这里是不保存文件到磁盘解决方案:

HSSFWorkbook workbook = new HSSFWorkbook(); 

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 
    workbook.write(outputStream); 

    InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); 
    StreamedContent streamedContent = new DefaultStreamedContent(inputStream, "application/xls", "output.xls");