Servlet-将响应导出到Excel文件 [英] Servlet - export response to Excel file

查看:90
本文介绍了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,然后使用StringBuffer data = (StringBuffer) getServletContext().getAttribute("test");从另一个servlet检索数据.

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天全站免登陆