我有一个链接到Excel 2007工作表的网页。它是.xlsx文件中的上传详细信息,并以.csv文件下载。当我点击下载链接并尝试打开时,我会得到通常的对话框来打开/保存Excel文件。点击'打开',我收到以下警告信息 -
您要打开的文件,' filename.csv'格式与文件扩展名指定的格式不同。在打开文件之前,请验证文件是否已损坏且是否来自受信任的源。你想现在打开文件吗?
我用Java开发了这段代码
private void downloadExcelSheet(HSSFWorkbook workbook, String sheetName){
OutputStream out = null;
try{
ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
workbook.write(outByteStream);
byte[] bytes = outByteStream.toByteArray(); //workbook.getBytes()
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
response.reset();
String disHeader = "Attachment;Filename=\""+sheetName+".csv\"";
response.addHeader("Content-Disposition", disHeader);
response.setContentType("text/csv");
//response.setHeader("Content-Disposition", "attachment; filename=\""+sheetName+".csv");
//response.setContentType("text/csv");
response.setContentLength(bytes.length);
out = response.getOutputStream();
out.write(bytes);
out.flush();
}catch(IOException ioe){
ioe.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
if(out!=null){
out.close();
}
}catch(IOException io){
io.printStackTrace();
}
}
}