我希望我的 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/poi/hssf/usermodel/HSSFWorkbook.html http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFWorkbook.html
您的问题的问题在于您正在混合 OutputStreams 和 InputStreams。输入流是您读取的内容,输出流是您写入的内容。
这就是我将 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 读取这些字节,可以轻松完成此操作,但我不推荐这样做。您现有的方法作为通用 Pipe 实现会更有用,您可以在其中将数据从 InputStream 传输到 OutputStream,但编写 POI 对象时不需要它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)