【问题标题】:Write into excel file using StreamingOutput object. (java.lang.ClassCastException)使用 StreamingOutput 对象写入 excel 文件。 (java.lang.ClassCastException)
【发布时间】:2017-04-27 01:36:16
【问题描述】:

我有一个返回 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 创建一个 SXSSFWorkbook 类型的新对象。难怪你在那里得到例外。您应该创建一个新行/单元格并在 cell.setValue() 上调用 stream.write()
  • 只是为了确定,你重写了那个类吗?来自 apache 的 SxSSFWorkbook 似乎没有实现流输出。
  • @Tosh 不,我没有重写 SXSSFWorkbook 类。如果 apache 没有实现 StreamingOutput 那么有没有其他方法可以将 StreamingOutput 对象写入 excel 文件?换句话说,我的意思是任何可以从 StreamingOutput 转换并且可以被 SXSSFWorkbook 用来写入 excel 的中间对象。
  • @YogeshPatel 我没有注意到,直到修复我的评论为时已晚。您的代码中没有任何内容需要工作簿,您可以轻松删除它并将流式输出保存到文件中。假设您的流输出已经正确格式化,则没有理由进行类型转换。如果您出于某种不明显的原因需要它,您应该重写您的问题或创建一篇关于如何将输出格式化为 xml 文件的新帖子。

标签: java excel apache-poi fileoutputstream


【解决方案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 了解更多信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-25
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    • 2013-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多