我不确定问题出在哪里,但我正在使用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()
。或许会有帮助。 - user432