问题
I have a list of Users and Non-users list which I am putting it in a jsp page by using a for loop and iterating thru html table and . How do I export the data to CSV at the server side. Exporting the data to CSV in the client side is complicated. I have very less knowledge wrt to J2EE. So please help me with this.If you can suggest me an approach, I can follow that..
回答1:
i was able to do this.
Req:On clicking a button in jsp it should export to CSV
jsp code
<div>
<input type="button" name="exporttocsv" onclick="window.open('${pageContext.request.contextPath}/GetUserDetails?exporttocsv=yes','toolbar=no','location=no','status=no','menubar=no','scrollbars=yes','resizable=yes','width=10','height=100');" value="Export to CSV"/>
</div>
GetUserDetails is my servlet.
Servlet side code.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("here inside get method");
String clickevent=request.getParameter("exporttocsv");
if(clickevent!=null &&clickevent.equalsIgnoreCase("yes"))
{
System.out.println("IN here....... download csv file...");
//Getting the list from a session and iterating through the list
HttpSession session = request.getSession();
List<User> nonusers = (List<User>)session.getAttribute("nonUserList");
response.setHeader("Content-type","application/csv");
response.setHeader("Content-disposition","inline; filename=test.csv");
PrintWriter out = response.getWriter();
out.println("Device Name,Non-Users");
for(User nonUser: nonusers)
{
out.println(nonUser.getDeviceName()+","+ nonUser.getCecId());
}
out.flush();
out.close();
}
Thanks for your help!!
来源:https://stackoverflow.com/questions/23836728/how-to-export-the-data-in-a-list-to-a-csv-file-in-the-server-side