使用StreamingOutput对象写入excel文件。 (java.lang.ClassCastException)

时间:2016-12-12 08:12:56

标签: java excel apache-poi fileoutputstream

我有一个返回 StreamingOutput 对象的方法。我想将此 StreamingOutput 对象写入excel文件。我写了下面的代码,它给了我java.lang.ClassCastException例外。

StreamingOutput stream = getStreamObject();
    SXSSFWorkbook workBook = (SXSSFWorkbook) stream; //Exception occurs here 

    FileOutputStream fileOut = new FileOutputStream("/save/excel/file/here");
    workBook.write(fileOut);
    fileOut.flush();
    fileOut.close();

所以,请帮我解决这个问题。提前谢谢。

1 个答案:

答案 0 :(得分:1)

必须重写StreamingOutput写入方法才能返回输出对象。这是一个例子:

public Response streamExample(){
        StreamingOutput stream = new StreamingOutput() {
            @Override
            public void write(OutputStream out) throws IOException, WebApplicationException {
                Writer writer = new BufferedWriter(new OutputStreamWriter(out));
                for (int i = 0; i < 10000000 ; i++){
                    writer.write(i + " ");
                }
                writer.flush();
            }
        };
        return Response.ok(stream).build();
    }

请查看Docs of Streaming outputhere了解详情