您好我一直在尝试编写代码以便我可以生成excel表并在用户点击下载按钮时下载....我已经成功生成excel表但我已经尝试下载相同的但我没有成功。
我使用的方法是:
public void download() throws IOException {
File file = new File("D:\\pdf\\carrierReport7.xls");
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
response.setHeader("Content-Type", "application/vnd.ms-excel");
OutputStream outputStream = response.getOutputStream();
FileInputStream fileInputStream = new FileInputStream(file);
byte[] bytesBuffer = new byte[2048];
int bytesRead = 0;
while ((bytesRead = fileInputStream.read(bytesBuffer)) > 0) {
outputStream.write(bytesBuffer, 0, bytesRead);
}
outputStream.flush();
fileInputStream.close();
outputStream.close();
facesContext.responseComplete();
}
jsf命令:
答案 0 :(得分:0)
这就是我在JSF 2中做类似的事情,不知道你在用什么版本。
public void downloadAttachment(Attachment attachment) throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
ec.setResponseContentType(ec.getMimeType(attachment.getFilename()));
ec.setResponseContentLength(attachment.getFilesizeBytes().intValue()); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + attachment.getFilename() + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
OutputStream output = ec.getResponseOutputStream();
output.write(attachment.getFileData());
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed. }
}
答案 1 :(得分:0)
我不知道是否检查了这个,但是必须在commandButton中声明ajax =“ false” ...
<p:commandButton ajax="false"
..........
</p:commandButton>