题
我想我的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 /组织/阿帕奇/ POI / HSSF /的usermodel / HSSFWorkbook.html
解决方案
你的问题的问题是,你混合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对象更加有用。
其他提示
可以创建从对象的InputStream。
public InputStream generateApplicationsExcel() {
HSSFWorkbook wb = new HSSFWorkbook();
// Populate a InputStream from the excel object
return new ByteArrayInputStream(excelFile.getBytes());
}
我想我明白你正在试图做的(也许我下冲,虽然)是什么
你并不真的需要那么多码 - 检查出写入方法 -
HSSFWorkbook wb = new HSSFWorkBook();
//populate
ServletOutputStream out = response.getOutputStream();
try {
wb.write(out);
out.flush();
}
catch (IOException ioe) {
//whatever
}
out.close();
据我记得当我的工作瓦特/ POI这就是我所做的。如果你在里面一个web框架,你可能不得不finaggle它,这样的框架不会尝试做一些与该ServletOutputStream的你已经关闭后。如果尝试,你会得到一个异常抛出告诉你的输出流已经关闭。
不隶属于 StackOverflow