我需要从jsp生成xls文件。
这是生成xls的代码。
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
java.io.File fn=new java.io.File(this.getServletContext().getRealPath("/")+"BillSummaryReport.xls");
if(!fn.exists()){
fn.createNewFile();
}
System.out.println(this.getServletContext().getRealPath("/")+"BillSummaryReport.xls");
//FileOutputStream fileOut = new FileOutputStream(f);
java.io.FileInputStream fin = new java.io.FileInputStream(fn);
ServletOutputStream outStream =response.getOutputStream();
hwb.write(response.getOutputStream());
response.setHeader("Content-Disposition","attachment;filename=BillSummaryReport.xls");
byte[] buffer = new byte[1024];
int n = 0;
while ((n = fin.read(buffer)) != -1) {
outStream.write(buffer, 0, n);
System.out.println(buffer);}
outStream.flush();
fin.close();
outStream.close();
} catch( Exception ex ) {
System.out.println(ex);
}
当我尝试运行应用程序时,会出现这样的错误。
>Sep 19, 2014 11:45:28 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [jsp] in context with path [/Midrest] threw exception [java.lang.IllegalStateException: getOutputStream() has already been called for this response] with root cause
java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:636)
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:213)
at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:125)
at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:118)
at org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:194)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
答案 0 :(得分:0)
您无法使用包含(写入)文本的jsp文件来发送回文件(例如xls)。 Jsp文件(编译成servlet)将尝试使用response.getWriter()
写入输出。
由于您调用response.getOutputStream()
来发送文件,因此尝试调用response.getWriter()
来编写HTML数据的jsp文件(servlet)将失败,因为这两种方法中只有一种(getOutputStream()
和可以使用getWriter()
)。
如果要发回文件,请使用简单的Servlet
而不是jsp文件。或者如果你必须,你可以使用jsp,但是你不能在输出中写任何东西,甚至不能换行。最好是使用Servlet
。