gpt4 book ai didi

java - 如何通过servlet打开Excel文件

转载 作者:行者123 更新时间:2023-12-02 08:13:48 26 4
gpt4 key购买 nike

我使用 jxls.jar 库将数据导出为 Excel 格式并存储在 *.xls 格式的文件中。使用 servlet 完成文件写入过程后,如何打开或升级对话框以打开或保存此文件写入文件的所有过程都是在单独的函数中完成的..

最佳答案

据我了解,您将 Excel 文件作为 File 对象,并且您希望将其作为下载提供给客户端。您需要将 Content-Disposition header 设置为 attachment,以便让客户端显示“另存为”对话框。您还需要设置 Content-Type header ,让客户端知道它是什么文件类型,以便它最终可以将正确的应用程序与其关联,以应对最终用户想要打开的情况立即吧。最后,最好设置 Content-Length header ,因为它可以提高服务性能(否则 Servlet API 将回退到分块编码,这需要更多的字节和处理时间)。

设置正确的 header 后,只需将 File 中的 InputStream 写入 HttpServletResponse 的 OutputStream 即可 通常的 Java IO 方式。

private static final int DEFAULT_BUFFER_SIZE = 8192; // 8KB.
// ...

File file = createExcelFileSomehow();
// ...

response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setHeader("Content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");

BufferedInputStream input = null;
BufferedOutputStream output = null;

try {
input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
for (int length; (length = input.read(buffer)) > -1;) {
output.write(buffer, 0, length);
}
} finally {
if (output != null) try { output.close(); } catch (IOException ignore) {}
if (input != null) try { input.close(); } catch (IOException ignore) {}
}

关于java - 如何通过servlet打开Excel文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6841998/

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