Servlet - 导出对Excel文件的响应 [英] Servlet - export reponse to Excel file

查看:95
本文介绍了Servlet - 导出对Excel文件的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法将响应从servlet导出到excel文件。请参阅以下代码:

I'm unable to export the response from a servlet to an excel file. Please see the code below :

Test.java:

Test.java :

 @Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html");
out = response.getWriter();
out.print("<form name=\"test\" method=\"post\" action=\"Export\">");
out.print("<table border=\"1\" cellpadding=\"3\" bordercolor='black'");
out.print("<tr>");
out.print("<td>1</td>");
out.print("<td>hello how are you?</td>");
out.print("</tr>");
out.print("</table>");
out.print("<td><input type=\"submit\" name =\"submit1\" value=\"Export To Excel\"></td>");
out.print("</form>");

点击时提交按钮生成不包含任何值的Excel表。请参阅点击提交按钮时调用的 Export.java

The submit button when clicked produce an excel sheet which doesn't contain any values. See the Export.java which is called when submit button is clicked.

Export.java

Export.java

public class Export extends HttpServlet {

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    String submit1 = request.getParameter("submit1");
   if (submit1 != null) {
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=users.xls");
    }
}
}

另外,如果我在 Test.java 中写下面的代码,它的工作正常和excel表确实包含表值。

Also, it has been observed that if i write the below code in Test.java, its working fine and the excel sheet does contain the table values.

response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=users.xls");

有没有办法转发 Export.java Test.java 当提交按钮被点击。

Is there any way to forward the output of Export.java to Test.java when the submit button is clicked.

推荐答案

最后,我找到了一个解决方案!我将所有的 out.print()东西存储到一个 StringBuffer 中。然后使用 getServletContext()。setAttribute(test,Buffer); 我将整个内容转发到另一个servlet中,从其他servlet转发我使用 StringBuffer data =(StringBuffer)getServletContext()。getAttribute(test);

Finally, I found a solution! I stored all the out.print() stuff into a StringBuffer. Then using getServletContext().setAttribute("test", Buffer); I forwarded the whole content into another servlet and from the other servlet I retrieved the data using StringBuffer data = (StringBuffer) getServletContext().getAttribute("test");.

最后,

response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=sample.xls");
response.getWriter().write(data.toString());`

工作。

这篇关于Servlet - 导出对Excel文件的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆