gpt4 book ai didi

java - 如何从 HSSFWorkbook 对象获取输入流

转载 作者:搜寻专家 更新时间:2023-10-30 21:28:02 25 4
gpt4 key购买 nike

我希望我的 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

最佳答案

你的问题是你混合了 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 读取这些字节,可以很容易地做到这一点,但我不推荐这样做。您现有的方法作为通用 Pipe 实现会更有用,您可以在其中将数据从 InputStream 传输到 OutputStream,但您不需要它来编写 POI 对象。

关于java - 如何从 HSSFWorkbook 对象获取输入流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/378883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com