我不确定问题是什么,但我正在使用Java和Jasper生成一个excel文件 正确地,我想立即将文件以xlsx格式下载到客户端站点,但该文件正在以.xhtml扩展名下载。我需要做什么?我正在使用 JSF。
这是我的方法:
public void generateOutStandingDCReportXLS() {
Connection conn = null;
try {
conn = db.getDbConnection();
Map parameters = new HashMap();
ClassLoader classLoader = getClass().getClassLoader();
InputStream logourl = classLoader.getResourceAsStream("/com/bi/jrxml/simba_logo.jpg");
InputStream stainurl = classLoader.getResourceAsStream("/com/bi/jrxml/coffee_stain.png");
parameters.put("logo", logourl);
parameters.put("stain", stainurl);
InputStream url = classLoader.getResourceAsStream("/com/bi/jrxml/Outstanding_DC.jrxml");
JasperReport jasperReport = JasperCompileManager.compileReport(url);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn);
ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
String path = (String) ctx.getAttribute("reportdir");
File f = new File(path);
if (!f.exists()) {
f.mkdirs();
}
String reportDestination = f.getAbsolutePath() + "/OutStanding_DC_Report" + ".xlsx"; //This is generated Correctly
File xlsFile = new File(reportDestination);
JRXlsxExporter Xlsxexporter = new JRXlsxExporter();
Xlsxexporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
Xlsxexporter.setParameter(JRExporterParameter.OUTPUT_FILE, xlsFile);
Xlsxexporter.exportReport();//File is generated Correctly
FileInputStream fis = new FileInputStream(new File(reportDestination));
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
IOUtils.copy(fis, response.getOutputStream());
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=" + "OutStanding_DC_Report" + ".xlsx"); //This is downloaded as .xhtml
response.flushBuffer();
fis.close();
} catch (JRException asd) {
System.out.println(asd.getMessage());
} catch (IOException asd) {
System.out.println(asd.getMessage());
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException asd) {
System.out.println(asd.getMessage());
}
}
}
服务器端的文件具有正确的扩展名,但要下载的文件具有.xhtml扩展名。
在IOUtils.copy()
之前调用setContentType()
和setHeader()
。
调用response.getOutputStream()
后,将发送标头。
斯坦利,你仍然面临同样的问题吗? 如果是,请尝试在下面设置字符串
response.setContentType()
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
即
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
而不是
application/vnd.ms-excel i.e. response.setContentType("application/vnd.ms-excel");
希望这会有所帮助。