どのように私はHSSFWorkbookオブジェクトからの入力ストリームを取得することができます
-
22-08-2019 - |
質問
私は自分の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の/ポイ/ HSSF / usermodel / HSSFWorkbook.htmlする
解決
あなたの質問の問題は、あなたがOutputStreamsと、入力ストリームを混合していることです。 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データを格納した入力ストリームにTHATを有効にする必要があると思います再利用、既存のコードに望んでいた場合。それは簡単に、その後に、ByteArrayInputStreamを使用して、それらのバイトを読み込む、ByteArrayOutputStreamに書き込むことによって行うことと思いますが、私はそれをお勧めしません。あなたの既存の方法はへのInputStreamとOutputStreamのどこからあなたができるパイプデータ、一般的なパイプの実装としてより有用であろうが、あなたはPOIオブジェクトを書き込むためにそれを必要としません。
他のヒント
あなたがオブジェクトからInputStreamを作成することができます。
public InputStream generateApplicationsExcel() {
HSSFWorkbook wb = new HSSFWorkbook();
// Populate a InputStream from the excel object
return new ByteArrayInputStream(excelFile.getBytes());
}
私は、私はあなたが(多分私も、アンダーシュートしています)何をしようとして理解だと思います。
あなたは本当に多くのコードを必要としない - writeメソッドをチェックアウトする -
HSSFWorkbook wb = new HSSFWorkBook();
//populate
ServletOutputStream out = response.getOutputStream();
try {
wb.write(out);
out.flush();
}
catch (IOException ioe) {
//whatever
}
out.close();
私は私がやったことだ/ POI wが働いていたときに私が覚えている限り。あなたがWebフレームワークの中にいる場合は、フレームワークは、あなたがそれを閉じた後にそのServletOutputStreamをして何かをしようとしないように、それをfinaggleする必要があります。それはしようとする場合は、出力ストリームがすでに閉じられていることを知らせる例外投げを取得します。