当前位置:  开发笔记 > 编程语言 > 正文

如何从HSSFWorkbook对象获取输入流

如何解决《如何从HSSFWorkbook对象获取输入流》经验,为你挑选了1个好方法。

我希望我的Web应用程序用户将一些数据下载为Excel文件.

我有下一个函数在响应对象中发送输入流.

public static void sendFile(InputStream is, HttpServletResponse response) throws IOException {
        BufferedInputStream in = null;
        try {
            int count;
            byte[] buffer = new byte[BUFFER_SIZE];
            in = new BufferedInputStream(is);
            ServletOutputStream out = response.getOutputStream();
            while(-1 != (count = in.read(buffer)))
                out.write(buffer, 0, count);
            out.flush();            
        }   catch (IOException ioe) { 
            System.err.println("IOException in Download::sendFile"); 
            ioe.printStackTrace();
        } finally {
            if (in != null) {
                try { in.close(); 
                } catch (IOException ioe) { ioe.printStackTrace(); }
            }   
        }
    }

我想将我的HSSFWorkbook对象转换为输入流并将其传递给前一个方法.

public InputStream generateApplicationsExcel() {
    HSSFWorkbook wb = new HSSFWorkbook();
    // Populate the excel object
    return null; // TODO. return the wb as InputStream 
}

http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFWorkbook.html



1> Mr. Shiny an..:

您的问题的问题是您正在混合OutputStreams和InputStreams.InputStream是您读取的内容,OutputStream是您写入的内容.

这就是我如何将POI对象写入输出流.

// this part is important to let the browser know what you're sending
response.setContentType("application/vnd.ms-excel");
// the next two lines make the report a downloadable file;
// leave this out if you want IE to show the file in the browser window
String fileName = "Blah_Report.xls";
response.setHeader("Content-Disposition", "attachment; filename=" + fileName); 

// get the workbook from wherever
HSSFWorkbook wb = getWorkbook();
OutputStream out = response.getOutputStream();
try {
   wb.write(out);
}       
catch (IOException ioe) { 
  // if this happens there is probably no way to report the error to the user
  if (!response.isCommited()) {
    response.setContentType("text/html");
    // show response text now
  }
}

如果您想重新使用现有代码,则必须将POI数据存储在某处,然后将其转换为输入流.这可以通过将其写入ByteArrayOutputStream,然后使用ByteArrayInputStream读取这些字节来轻松完成,但我不推荐它.您现有的方法作为通用管道实现会更有用,您可以将数据从InputStream传递到OutputStream,但是您不需要它来编写POI对象.

推荐阅读
LEEstarmmmmm
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有