Servlet - export response to Excel file

2020-03-26 08:22发布

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

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>");

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

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");
    }
}
}

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");

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

2条回答
Deceive 欺骗
2楼-- · 2020-03-26 08:48

You have to call setContentType before printing the response. You can't print your HTML table and then have the user click a button that takes them to a completely different servlet that does nothing but set the setContentType to Excel and expect that somehow it remembers your HTML table. You also should really look into getting an Excel library for Java (e.g. Apache POI) and using application/msexcel rather than relying on application/vnd.ms-excel to convert HTML to Excel, if this project is meant to have any real-world usefulness.

查看更多
Deceive 欺骗
3楼-- · 2020-03-26 08:53

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");.

And finally,

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

did the job.

查看更多
登录 后发表回答