我有一个返回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();


所以,请帮我解决这个问题。先感谢您。

最佳答案

必须重写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以获取更多信息

10-08 19:26